我有两个类:OuterClass和InnerClass。 InnerClass是OuterClass的私有成员,应该在OuterClass构造函数中使用InnerClass(int)构造函数创建,但是仍会调用默认的InnerClass构造函数。

InnerClass.hpp:

#ifndef INNERCLASS_HPP_
#define INNERCLASS_HPP_

class InnerClass {
public:
    int a;
    InnerClass();
    InnerClass(int);
    ~InnerClass();
};

#endif /* INNERCLASS_HPP_ */


InnerClass.cpp:

#include "InnerClass.hpp"
#include <iostream>

InnerClass::InnerClass() {
    a = 1;
    std::cout << "inner class constructed, a = " << a << std::endl;
}
InnerClass::InnerClass(int x) {
    a = x;
    std::cout << "inner class constructed, a = " << a << std::endl;
    //automatically: object InnerClass (a=3) is destroyed here...
}
InnerClass::~InnerClass() {
    std::cout << "inner class destructed, a = " << a << std::endl;
}


OuterClass.hpp:

#ifndef OUTERCLASS_HPP_
#define OUTERCLASS_HPP_

#include "InnerClass.hpp"

class OuterClass {
private:
    InnerClass blah;
public:
    OuterClass();
    ~OuterClass();
    void doSth();
};

#endif /* OUTERCLASS_HPP_ */


OuterClass.cpp:

#include "OuterClass.hpp"
#include <iostream>

OuterClass::OuterClass() {
    // automatically: blah = InnerClass();
    std::cout << "outer class constructing started, blah.a = " << blah.a << std::endl;
    blah = InnerClass(3);
    std::cout << "outer class constructed" << std::endl;
}

OuterClass::~OuterClass() {
    std::cout << "outer class destructed" << std::endl;
}

void OuterClass::doSth() {
    std::cout << "doSth: " << blah.a << std::endl;
}


主要:

#include "OuterClass.hpp"
#include <iostream>

int main(int argc, char** argv) {
    std::cout << "Compiled at " << __TIME__ << std::endl;

    OuterClass x = OuterClass();
    x.doSth();

    std::cout << "done" << std::endl;
}


输出:

Compiled at 12:11:12
inner class constructed, a = 1 //this is unexpected
outer class constructing started, blah.a = 1 //this should be random data
inner class constructed, a = 3
inner class destructed, a = 3 //this is unexpected
outer class constructed
doSth: 3
done
outer class destructed
inner class destructed, a = 3


问题:


为什么在OuterClass构造函数的开头调用InnerClass的默认构造函数?
什么和为什么在OuterClass构造函数中被破坏(“内部类被破坏,a = 3 //这是意外的”)?
看来a = 3的InnerClass对象在OuterClass构造函数中被破坏了,为什么方法doSth()返回3而不是随机数据呢?
为什么从InnerClass.hpp和InnerClass.cpp文件中删除InnerClass()构造函数会导致OuterClass.cpp文件中OuterClass构造函数的编译时错误?该错误表明未找到InnerClass()定义。

最佳答案

在构造函数中使用initializer-list。

OuterClass::OuterClass() : blah(3) {
    // automatically: blah = InnerClass();
    std::cout << "outer class constructing started, blah.a = " << blah.a << std::endl;
    std::cout << "outer class constructed" << std::endl;
}


自从您使用

OuterClass::OuterClass() {
    // automatically: blah = InnerClass();
    std::cout << "outer class constructing started, blah.a = " << blah.a << std::endl;
    blah = InnerClass(3);
    std::cout << "outer class constructed" << std::endl;
}


首先,对于初始化,blah将被称为默认c-tor,在blah = InnerClass(3);中,它将创建临时对象并将其复制到blah,此字符串将被称为临时对象的析构函数。

10-08 11:15