使用"this"作为复制构造函数的参数

6 c++

我有一个c ++类,假设它叫做c,我想在其中一个方法中使用隐式复制构造函数,如下所示:

c c::do_something() {
  c copy = this; //I want implicit copy constructor here!
  copy.something_else(); 
  //........//
  return copy;
}
Run Code Online (Sandbox Code Playgroud)

但是,gcc返回此错误:

错误:从'c*const'到'long unsigned int'的无效转换

(我有来自long unsigned int的另一个构造函数)

......就好像复制构造函数不存在一样.我究竟做错了什么?

tli*_*iff 21

是一个指向对象的指针,所以它应该是

c copy = *this;
Run Code Online (Sandbox Code Playgroud)

  • A a = b; 实际上永远不会调用默认的 ctor + 赋值运算符。在某些情况下,不仅仅会调用复制构造函数(例如强制转换运算符),但您永远不会获得默认构造函数+赋值运算符。请参阅 C++ 标准中的复制初始化。 (2认同)

Ecl*_*pse 6

相当不谈,但它不会真正适合评论,似乎存在一些分歧.尝试使用这段代码来了解何时调用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)
}
Run Code Online (Sandbox Code Playgroud)