小编Ros*_*han的帖子

导致代码无法编译的C++拷贝构造函数(gcc)

我有以下不编译的代码.编译器错误是:

"error: no matching function to call B::B(B)",
candidates are B::B(B&) B::B(int)"
Run Code Online (Sandbox Code Playgroud)

代码在以下两个条件之一下编译:

  1. 取消注释功能B(const B&)
  2. 将'main'更改为以下内容

    int main()
    {
            A a;
            B b0;
            B b1 = b0;
            return 0;
    }
    
    Run Code Online (Sandbox Code Playgroud)

如果我做1,代码编译,但从输出它说它调用'非const复制构造函数'.

谁能告诉我这里发生了什么?

using namespace std;
class B
{
    public:
    int k;
     B()
     { 
        cout<<"B()"<<endl; 
     }
     B(int k) 
     { 
        cout<<"B(int)"<<endl;
        this->k = k;
     }
     /*B(const B& rhs) { 
        cout<<"Copy constructor"<<endl;
        k = rhs.k;
     }*/
     B(B& rhs) 
     { 
        cout<<"non const Copy constructor"<<endl;
        k = rhs.k;
     }
     B operator=(B& rhs)
     {
        cout<<"assign operator"<<endl; …
Run Code Online (Sandbox Code Playgroud)

c++ constructor copy const reference

2
推荐指数
1
解决办法
1630
查看次数

标签 统计

c++ ×1

const ×1

constructor ×1

copy ×1

reference ×1