【发布时间】:2020-05-26 13:33:42
【问题描述】:
我有一个像下面这样的课程:
#pragma once
#include <atomic>
class MyClassAnother {
public:
MyClassAnother(int val) : m_val(val) {
}
private:
int m_val;
};
还有一个类持有MyClassAnother的对象
#pragma once
#include "MyClassAnother.hpp"
class MyClass {
public:
MyClass() {
}
void Func() {
anotherClassObject = MyClassAnother(2);
}
private:
MyClassAnother anotherClassObject;
};
这里是main.cpp
#include "MyClass.hpp"
#include <iostream>
int main() {
MyClass object;
}
当然程序不会编译。而且是因为下面的错误
错误:“MyClass”的构造函数必须显式初始化成员 'anotherClassObject' 没有默认值 构造函数
问题:
但为什么?为什么我不能延迟初始化类成员?是否有一个默认构造函数并延迟使用真正的构造函数初始化它?那么这样做是不是一种反模式呢?
我知道这可以通过将MyClassAnother anotherClassObject 设为指针来解决。但在这种情况下,我希望将MyClassAnother anotherClassObject 作为成员对象或引用成员。
【问题讨论】:
标签: c++11 constructor default-constructor