所以这是我在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构造函数 汽车制造商 汽车破坏者
为什么没有输出Gearbox析构函数? (对我来说,汽车有一个参考他的变速箱是有意义的,因为变速箱应该存在,而汽车确实存在)
答案 0 :(得分:0)
这必须是编译器错误,可能与它首先允许引用初始化(这是Visual Studio扩展,不符合任何版本的实际,标准化C ++语言)有关。
我相信我可以使用在线VS编译器重现这个:
C ++编译器允许删除复制操作,即使它们包含这样的输出,但不包含构造函数和析构函数。
答案 1 :(得分:-2)
GearBox是否已实例化?
Car::Car(): speed(0), gearBox(GearBox())
{
cout << "Car constructor" << endl;
}
↓
Car::Car(): speed(0)
{
static GearBox inst;
gearBox = inst;
cout << "Car constructor" << endl;
}
修改强>
class Car
{
private:
int speed;
class GearBox { // referable
private:
int gear;
public:
GearBox() : gear(0) {
cout << "Gearbox constructor" << endl;
}
~GearBox() {
cout << "GearBox destructor" << endl;
}
};
GearBox* gearBox;
public:
Car();
~Car();
};
Car::Car(): speed(0)
{
static GearBox inst;
gearBox = &inst;
cout << "Car constructor" << endl;
}