复制构造函数调用

A copy constructor call

本文关键字:函数调用 复制      更新时间:2023-10-16

>我声明了一个这样的 Point 类:

class Point{
      private :  
      int a,b;  
      public :       
      Point(Point const &p) {
      a = p.a + 1;
      b = 0;
      }
      Point(){a=2; b=3;}
      int getX(){return a;}
      int getY(){return b;}
      };
 int main(){
   Point p1,p2;
   p2=p1;
   cout << p2.getX(); // 2
   cout << p2.getY(); // 3
  }

为什么不调用复制构造函数?

 int main(){
   Point p1;
   Point p2=p1;
   cout << p2.getX(); // 3
   cout << p2.getY(); // 0
}

这是复制构造

Point p2=p1;  // p2 is constructed here.
              // This is shorthand for Point p2(p1);

这是作业

p2=p1;  // p2 already exists (it was created on the previous line).

赋值运算符的定义如下:

// If you don't define this the compiler will generate one for you.
Point& operator=(Point const& rhs)
{
     // Copy for rhs into this.
     return *this;
}

// The compiler generated one looks like this:
Point& operator=(Point const& rhs)
{
     a = rhs.a;
     b = rhs.b;
     return *this;
}

在第一个程序中

 int main(){
   Point p1,p2;
   p2=p1;
   ^^^^^

有 称为编译器隐式创建的复制赋值运算符。在此程序中,对象p2已使用默认构造函数创建

   Point p1,p2;

在第二个程序中

 int main(){
   Point p1;
   Point p2=p1;
   ^^^^^^^^^^^

确实有所谓的复制构造函数。

 Point p1,p2;
 p2=p1;

P2 已经构造,因此第二条语句调用赋值运算符

点 p1;点 p2=p1;

这里 p2 是复制构造的,因为它以前从未被构造过。

请考虑以下代码:

#include <iostream>
class A {
public:
  A() { std::cout << "Ctor calledn"; }
  A(const A&) { std::cout << "Copy Ctor calledn"; }
  A& operator=(const A&) { std::cout << "Assignment operator calledn"; return *this;}
};
int main() {
  A a,b;
  b = a;
  A c;
  A d = c;
}

其输出具有启发性:

Argento:Desktop marinos$ clang++ test.cpp -o test
Argento:Desktop marinos$ ./test
Ctor called
Ctor called
Assignment operator called
Ctor called
Copy Ctor called