对参数化构造函数的显式调用引发错误

Explicit call to parameterized constructor throws an Error

本文关键字:调用 错误 参数 构造函数      更新时间:2023-10-16

在创建对象时,我们可以隐式或显式调用构造函数

Base obj;
Base obj = Base(1,2);

这两种对象创建方法都运行良好,直到我在代码中包含了复制构造函数。这是代码片段。

#include<iostream>
using namespace std;
class Base {
    public:
    Base(int x, int y) {}
    Base() {}
    Base(Base& o){}
    private:
    int a;
    int b;
};
int main() {
    Base obj = Base(10,20);    /*This line throws error after including copy Ctor*/
    Base obj2 = obj;
}

我使用的是Linux g++编译器。错误:调用"Base::Base(Base)"没有匹配的函数

我是不是错过了什么。

复制构造函数应采用以下形式,以便使用Base(10,20) 创建临时对象

Base(const Base& o){}
 //  ~~~~ notice `const` 

或者,您可以在C++11中使用move构造函数,以允许临时对象

Base(Base &&o){}

您有两种可能性。要么像一样更改复制构造函数的声明

Base( const Base &o){}

或者添加一个移动构造函数

Base(Base &&o){}

例如

#include<iostream>
using namespace std;
class Base {
    public:
    Base(int x, int y) {}
    Base() {}
    Base(Base& o){}
    Base( Base && ){}
    private:
    int a;
    int b;
};
int main() {
    Base obj = Base(10,20);    /*This line throws error after including copy Ctor*/
    Base obj2 = obj;
}

代码的问题在于表达式Base(10,20)创建了一个临时对象,该对象只能与常量引用绑定。

事实上,您不需要为这个简单类显式定义复制构造函数。