【发布时间】:2023-04-07 10:41:01
【问题描述】:
这是我在 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 析构函数? (对我来说,汽车引用他的变速箱是有道理的,因为变速箱应该存在而汽车确实存在)
【问题讨论】:
-
您在使用 MSVS 吗?如果您注意到
gearBox(GearBox())是非法的,因为您将临时绑定到左值引用。 -
该代码不是有效的 C++。左值引用不绑定到右值。
-
@NathanOliver 是的,我正在使用 MSVS。好的那为什么程序编译成功了?我怎样才能做到这一点?
-
@Bunc 我编译是因为微软决定允许它编译。这是一个邪恶的扩展,应该被删除。您可以使用
const &捕获临时文件,但无法修改它。 -
我在 VS2013 中使用了你的代码。它有效,并且调用了两个析构函数。我也收到了警告 - C4413。 Gear的析构函数在Car的析构函数之前调用,这看起来很正常。这辆车只引用了 Gear。
标签: c++ class nested destructor private