bec666 2019-09-19 21:42 采纳率: 88%
浏览 317
已结题

运行结果为什么只有一个constructor呢?

#include <iostream>
using namespace std;
class A
{
    int a,b;
public:
    A(int i,int j):a(i),b(j){cout<<"constructor"<<endl;}
    ~A(){cout<<"destructor"<<endl;}
};
int main()
{
    A obj1(1,2);
    A obj2=obj1;
    return 0;
}

  • 写回答

3条回答 默认 最新

  • 白行峰 (花名) 领域专家: 系统编程技术领域 2019-09-19 22:30
    关注

    因为以下的赋值并没有调用它的显式构造函数,而是调用编译器生成的隐式拷贝构造函数。

    A obj2=obj1;
    

    如果我们自己写显式拷贝构造函数,就会打印。

    // test-c11.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    class A
    {
        int a, b;
    public:
        A(int i, int j) :a(i), b(j) { cout << "constructor" << endl; }
        A(A& a1) 
        {
            a = a1.a;
            b = a1.b;
            cout << "copy constructor" << endl;
        }
        ~A() { cout << "destructor" << endl; }
    };
    
    int main()
    {
        A obj1(1, 2);
        A obj2 = obj1;
        return 0;
    }
    

    输出

    constructor
    copy constructor
    destructor
    destructor
    
    评论

报告相同问题?