类类型作为私有成员,MVP

class types as private members, MVP?

本文关键字:成员 MVP 类型      更新时间:2023-10-16

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

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;