类类型作为私有成员,MVP
class types as private members, MVP?
由于最令人烦恼的解析,如果在类头中有一个私有成员定义,它是这样的类类型:
box newBox;
和box有一个不接受参数的构造函数,这是否意味着您必须将其设置为指针类型或引用类型?
你如何解决这个问题?能够以这种方式声明某些类,而不是不接受参数的类,似乎是不优雅的。还是我误解了什么?
,因为据我所知,如果它不接受参数,那么这不仅是一个定义,也是一个初始化。
class whatever
{
private:
box newBox; //is this not allowed because of the most vexing parse? because it's a
//header file and because of the MVP this is initialisation as well? or
//am I getting confused about something?
};
class box
{
public:
box();
}
下面的代码可以正常运行:
struct Foo {
}
struct Bar {
Foo foo;
}
没有MVP,没有歧义。一切都很好。在类声明中,Foo foo;
是成员声明。它不能在那里初始化,初始化是在构造函数中完成的(显式或隐式)(在本例中是Bar
)。
如果唯一的构造函数不接受参数,则这是规范构造函数,每次构造具有newBox
作为元素的类的实例时都会调用该构造函数。它仍然总是一个新的box
对象,尽管它看起来总是一样的。
你可以这样测试:
class foo {
public:
foo() {
std::cout << "Constructed a foo.n";
}
};
class bar{
foo afoo;
public:
bar() {}
};
int main() {
std::cout << "Request new bar: ";
bar bar1;
std::cout << "Request another new bar: ";
bar bar2;
return 0;
}
输出:Request new bar: Constructed a foo.
Request another new bar: Constructed a foo.
您的whatever
类没有问题,只是您需要将box
的定义移动到whatever
之前,以便在那里使用box
。当您创建whatever
的实例时,newBox
将使用box
类的默认构造函数初始化。
如果您想要明确初始化或以某种方式自定义它,您必须向whatever
类添加构造函数。例如:
class whatever {
private:
box newBox;
public:
whatever() : newBox() {
// ...
}
};
这是一个最令人烦恼的解析示例:
box newBox();
这不是:
box newBox;
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 多成员Constexpr结构初始化
- 类类型作为私有成员,MVP