我有两个类:OuterClass 和 InnerClass。InnerClass 是 OuterClass 的私有成员,应使用 InnerClass(int) 构造函数在 OuterClass 构造函数中创建,但仍会调用默认的 InnerClass 构造函数。
内部类.hpp:
#ifndef INNERCLASS_HPP_
#define INNERCLASS_HPP_
class InnerClass {
public:
int a;
InnerClass();
InnerClass(int);
~InnerClass();
};
#endif /* INNERCLASS_HPP_ */
内部类.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;
}
外部类.hpp:
#ifndef OUTERCLASS_HPP_
#define OUTERCLASS_HPP_
#include "InnerClass.hpp"
class OuterClass {
private:
InnerClass blah;
public:
OuterClass();
~OuterClass();
void doSth();
};
#endif /* OUTERCLASS_HPP_ */
外部类.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() 构造函数(从 InnerClass.hpp 和 InnerClass.cpp 文件中)会导致 OuterClass.cpp 文件中的 OuterClass 构造函数出现编译时错误?该错误表示未找到 InnerClass() 定义。