使用C ++类中的复杂函数初始化const成员 [英] Initialize const members using complex function in C++ class
问题描述
我有一个与3d网格一起工作的程序。这个网格有自己的类对象Grid,看起来像这样(简化版本):
I have a program that works with 3d grids. This grid has its own class object Grid that looks like this (simplified version):
class Grid
{
public:
Grid() { readDataFromInputFile(); }
private:
void readDataFromInputFile() {...} // this function reads the values for i, j, k from disk
int i; int j; int k;
};
现在我想做的是能够设置变量i,j和k作为const int,以避免他们意外地在其他函数中混乱。但我不能轻易地将它们设置在成员初始化列表中,因为它们必须从文件读取。我已经浏览了现有的讨论,但是我找不到关于这个问题的准确讨论。
What I would like to do now, is to be able to set the variables i, j and k as const int, to avoid messing them accidentally up in the other functions. I can however not easily set them in a member initializer list, because they have to be read from file. I have been browsing through the existing discussions but I couldn't find an accurate discussion on this problem.
有一个解决方案能够设置为const,仍然能够使用复杂的函数来检索数据吗?
Is there a solution to be able to set them as const, and still be able to use a complex function to retrieve the data? In my real application, there are of course much more variables to be read, that are not allowed to change after initialization.
推荐答案
在我的实际应用程序中,有更多的变量要读取,不要破坏一个责任原则: Grid
不应负责从文件加载自身,这是另一个组件的责任(例如一个简单的加载函数) :
Don't break the One Responsibility Principle: A Grid
should not be responsible of loading itself from a file, this is a responsibility of another component (For example a simple loading function):
class Grid
{
public:
Grid( int ii , int jj , int kk ) : i{ ii } , j{ jj } , k{ kk }
private:
const int i , j , k;
};
Grid loadGrid( constd std::string& filename )
{
...
};
这篇关于使用C ++类中的复杂函数初始化const成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!