c++ - 为什么在 C++ 中不为私有(private)嵌套类调用析构函数?

标签 c++ class nested destructor private

所以这是我在 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 编译器重现它:

Reproduction screenshot

C++ 编译器允许省略复制操作,即使它们包含这样的输出,但构造函数和析构函数除外。

关于c++ - 为什么在 C++ 中不为私有(private)嵌套类调用析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36435123/

相关文章:

c++ - 项目错误 : Unknown module(s) in QT: script?

c++ - ACE vs Boost vs Poco vs wxWidgets

python - 如何在 Python 中完全保存/读取类

java - 在类结构中找到正确的子类

php - mysql 查询在 codeigniter 中失败,但如果直接运行则有效

php - 在 PHP 中回显一个多维数组

java - 在 Eclipse 中,定义嵌套类

c++ - float 和 double 的大小

c++ - 是否可以在没有临时存储的情况下进行就地合并?

模板类中新结构的 C++ 语法