2016-03-15 156 views
-1

我已经声明了一个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 
} 

回答

0

在第一个程序

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

有被称为由编译器隐式创建的拷贝赋值运算符。 在这个程序中的对象p2使用默认构造函数

Point p1,p2; 

在tfhe第二方案

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

确实是有所谓的拷贝构造函数已经创建。

3

这是拷贝构造

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; 
} 
0
Point p1,p2; 
p2=p1; 

P2已经构造了第二条语句调用th e转让运营商

Point p1; 点p2 = p1;

这里p2是复制构造的,因为它以前没有被构建过。

考虑以下代码:

#include <iostream> 

class A { 
public: 
    A() { std::cout << "Ctor called\n"; } 
    A(const A&) { std::cout << "Copy Ctor called\n"; } 
    A& operator=(const A&) { std::cout << "Assignment operator called\n"; 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