对参数化构造函数的显式调用引发错误
Explicit call to parameterized constructor throws an Error
在创建对象时,我们可以隐式或显式调用构造函数
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)
创建了一个临时对象,该对象只能与常量引用绑定。
事实上,您不需要为这个简单类显式定义复制构造函数。
相关文章:
- C++模板类 - 继承调用错误的函数
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 使用 std::find 时没有匹配的函数调用错误
- 使用成员初始值设定项列表时没有匹配的函数调用错误
- C++调用错误签名的函数
- C++ 类成员调用错误 C3861
- C bool表达式作为函数参数调用错误的超载
- C ++尝试访问映射中的元素会给我一个不匹配的函数调用错误
- 当提供巨大的输入时,中止在堆栈操作程序中调用错误
- C++类静态成员函数调用错误
- 如何调查随机安卓原生函数调用错误?
- 引发实例后终止调用 - C++错误
- 如何修复传递参数时调用错误函数的主函数?(C++)
- 没有用于调用错误的匹配函数.将字符串推送到向量中
- 从括号内的initializer_list构造时,将调用错误的过载
- 为什么初始值设定项列表中的元素数会导致不明确的调用错误
- VC 15调用错误的复制构造函数以捕获lambda
- 在 C++ 中没有针对调用错误的匹配函数
- C++:函数调用错误:标识符"name"未定义,如果已定义?
- 为什么 GCC 在显式指定模板参数时会产生奇怪的错误并尝试调用错误的方法?