为什么类构造函数在通过复制初始化对象时不起作用

Why class constructor dont work when object initialization by copy?

本文关键字:初始化 对象 不起作用 复制 构造函数 为什么      更新时间:2023-10-16

为什么当我使用另一个对象的副本初始化类对象的构造函数时,它不起作用?

class Human
{
   int No;
   public:
       Human(int arg):No(arg)
       {
        cout<<"constructor Works"<<endl;
       }
};
int main()
{
    Human a{10}; // constructor Works for object a
    Human b{a};  //why b object's constructor dont work?
}

你需要一个复制构造函数,否则编译器将生成一个(它不输出任何内容)。加:

Human(const Human& h):No(h.No) { std::cout << "copy-ctor" << std::endl; }

"不起作用"是指运行代码后没有输出到屏幕吗?当然没有 - Human b{a}调用与Human a{10}完全不同的构造函数.它调用编译器生成的复制构造函数,其签名为:

Human(Human const& other)

如果您希望在复制构造时有输出,只需创建自己的输出:

class Human
{
    // ...
    Human(Human const& other)
        : No{other.No}
    {
        std::cout << "copy-constructorn";
    }
};