如果我有一个包含更多成员的类,并且其中一些成员依赖于其他成员,那么声明其成员的最佳方式是什么?例如:
class MyClass
{
private:
MyOb1 Obj1;
MyOb2 Obj2;
int i;
std::string str;
public:
MyClass(int iIn, const std::string& strIn)
: i(iIn), // here
str(strIn),
Obj1(i),
Obj2(i, str) {}
}
由于申报顺序的原因,出现了一些问题。我选择了那个顺序,因为它是一个最优顺序。我在 MyClass
的其他函数中需要这些值。这个问题的最佳解决方案是什么?
最佳答案
由于初始化顺序取决于它们在您的类中定义的顺序,因此忽略成员顺序:C++: Initialization Order of Class Data Members .
所以我只是将整数和字符串移到 MyOb1
和 MyOb2
上面,@Matt McNabb 也指出你应该使用在你的构造函数中传递的参数初始化 MyOb1/2 对象以避免歧义(明智的建议):
class MyClass
{
private:
int i;
std::string str;
MyOb1 Obj1;
MyOb2 Obj2;
public:
MyClass(int iIn, const std::string& strIn)
: i(iIn), // here
str(strIn),
Obj1(iIn),
Obj2(iIn, strIn) {}
}
引用标准第 12.6.2 节(最新的 draft 在第 266 页有这个):
5 Initialization shall proceed in the following order:
— First, and only for the constructor of the most derived class as described below, virtual base classes shall be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base class names in the derived class base-specifier-list.
— Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
— Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
— Finally, the body of the constructor is executed. [Note: the declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. ]
关于c++ - 类中成员声明顺序如果相互依赖,最优解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25033690/