我有一个c ++类,假设它叫做c,我想在其中一个方法中使用隐式复制构造函数,如下所示:
c c::do_something() { c copy = this; //I want implicit copy constructor here! copy.something_else(); //........// return copy; }
但是,gcc返回此错误:
错误:从'c*const'到'long unsigned int'的无效转换
(我有来自long unsigned int的另一个构造函数)
......就好像复制构造函数不存在一样.我究竟做错了什么?
这是一个指向对象的指针,所以它应该是
c copy = *this;
相当不谈,但它不会真正适合评论,似乎存在一些分歧.尝试使用这段代码来了解何时调用copy-constructors和赋值运算符:
class A { public: A() { cout << "A::A()\n"; } A(const A &) { cout << "A::A(const A &)\n"; } void operator =(const A &) { cout << "A::operator=(const A &)\n"; } }; int main() { A a; // default constructor A copy = a; // copy constructor (and no assignment operator) A copy2(a); // copy constructor (and no assignment operator) a = copy; // assignment operator A function(); // declares a function return A A b = A(); // default constructor (but no assignment operator) A b2 = A(a); // copy constructor (but no assignment operator) }