c++ - 复制构造函数中的初始化列表

标签 c++ struct

#include <iostream>
using namespace std;

struct A{
    A(){}
    A(const A&) {cout<<"1";}
};

struct B: A{
    B(){}
    B(const B&){}
};

struct C: A{
    C(){}
    C(const B&rhs):A(rhs){} 
};

struct D:A{
    D(){}
};

int main(){
    D d;
    D dcopy(d);
    C c;
    C ccopy(c);
    B b;
    B bcopy(b);
    }

当我运行这个程序时,我期望输出为:111,但它给出的输出为:11,请解释!!!

C(const B& rhs) : A(rhs) {}  // presence of this line has no influence on output,
                             // please explain, why?

最佳答案

B(const B&){}

此代码不输出任何内容,也不复制构造 A(它默认构造它)。所以 B bcopy(b) 不输出任何东西。也许你的意思是:

B(const B& rhs) : A(rhs) {}

关于c++ - 复制构造函数中的初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20845482/

相关文章:

c++ - AVR C++ uint32_t 奇怪的行为

c++ - 线程内存问题(tinythread,C++)

在 C 中创建具有三个属性的结构数组的概念

c - 结构上的指定初始化程序会导致 strcpy 和 realloc 中出现段错误

c++ - 从 QByteArray 使用 libjpeg 加载 jpeg 图像纹理

c++ - 如何用实际值替换转义符号?

c++ - mktime() 给出的结果与 Howard Hinnant 的日期库(基于 std::chrono)不同

c - 指向结构中 char 的灵活指针数组

c++ - 序列化结构的 STL 映射

C++ void指针获取结构