2016-03-15 175 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