类类型作为私有成员,MVP?

时间:2011-10-13 11:57:06

标签: c++

由于最令人烦恼的解析,如果你在类标题中有一个私有成员定义,这是一个类类型:

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();
}

4 个答案:

答案 0 :(得分:1)

以下工作正常:

struct Foo {
}

struct Bar {
    Foo foo;
}

没有MVP,没有歧义。一切都好。在类声明中Foo foo;是一个成员声明。它无法在那里初始化,初始化在构造函数中完成(显式或隐式)(在本例中为Bar)。

答案 1 :(得分:0)

如果唯一的构造函数不接受任何参数,那么这就是每次构造一个以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.

答案 2 :(得分:0)

您的whatever课程没有任何问题,除了您需要在box之前移动whatever的定义,以便box可以在那里使用whatever 。当您创建newBox的实例时,box将使用whatever类的默认构造函数进行初始化。

如果您想明确初始化或以某种方式对其进行自定义,则必须向class whatever { private: box newBox; public: whatever() : newBox() { // ... } }; 类添加构造函数。例如:

{{1}}

答案 3 :(得分:0)

这是最令人烦恼的解析的一个例子:

box newBox();

这不是:

box newBox;
相关问题