所以这是我在 Car.h 中的代码
#pragma once
#include<iostream>
#include<string>
using namespace std;
class Car
{
private:
int speed;
class GearBox;
GearBox& gearBox;
public:
Car();
~Car();
};
class Car::GearBox {
private:
int gear;
public:
GearBox();
~GearBox();
};
在 Car.cpp 中我有
#include"Car.h"
Car::Car(): speed(0), gearBox(GearBox())
{
cout << "Car constructor" << endl;
}
Car::~Car()
{
cout << "Car destructor" << endl;
}
Car::GearBox::GearBox(): gear(0)
{
cout << "Gearbox constructor" << endl;
}
Car::GearBox::~GearBox()
{
cout << "GearBox destructor" << endl;
}
我的主要是:
#include"Car.h"
int main() {
{
cout << "Starting program!" << endl;
Car car;
}
system("PAUSE");
return 0;
}
程序的结果是: 启动程序! 变速箱构造函数 汽车制造商 汽车破坏者
为什么没有输出Gearbox析构函数? (对我来说,car 引用他的变速箱是有道理的,因为变速箱应该存在,而 car 确实存在)
最佳答案
这一定是一个编译器错误,可能与它首先允许引用初始化这一事实有关(这是一个 Visual Studio 扩展,不符合实际的标准化 C++ 语言的任何版本)。
我相信我可以使用在线 VS 编译器重现它:
C++ 编译器允许省略复制操作,即使它们包含这样的输出,但构造函数和析构函数除外。
关于c++ - 为什么在 C++ 中不为私有(private)嵌套类调用析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36435123/