#include
#include
using namespace std;
class Object {
public:
Object() {
std::cout << "build this object!" << std::endl; }
Object(Object& obj) {
std::cout << "copy this object! " << std::endl;
}
virtual ~Object() {
std::cout << "destruct this object! " << std::endl; }
};
//int Object::num=0;
void f(Object obj){ }
int main() {
Object obj;
// function calling
f(obj);
// vector
std::vector v;
v.push_back(obj);
return 0;
}
编译时提示“rror C2558: class 'Object' : no copy constructor available”,注释掉复制构造函数,编译就能通过,不报错,这是什么原因
Object(const Object& obj) {
class Object {
public:
Object() {
std::cout << "build this object!" << std::endl; }
Object(const Object& obj) {
std::cout << "copy this object! " << std::endl;
}
virtual ~Object() {
std::cout << "destruct this object! " << std::endl; }
};
//int Object::num=0;
void f(Object obj){ }
int main() {
Object obj;
// function calling
f(obj);
// vector
std::vector<Object> v;
v.push_back(obj);
return 0;
}
问题出在 v.push_back(obj);
这个函数有两个重载函数,
一个是需要传一个常引用作为参数 const Object&
二个是需要一个移动参数 Object&&
但是你只实现了 Object& 的拷贝构造函数,所以和这两个签名都对不上。
修改方法,拷贝函数的参数前面加上 const,这个也是常规做法,不知道你为啥不加const; 或者 实现一个移动语义的构造函数。
另外你注释掉 拷贝构造函数以后就能编译通过是因为如果自己不实现则系统会默认实现全套的函数,就是 const Object& 和 Object&& 的构造函数都会被实现,但是如果你自己实现了任何一个,则系统不会帮你实现了。