0
我有一個類定義如下:C++隱含的拷貝構造函數和賦值操作符
#include <iostream>
using namespace std;
class Point
{
int x, y;
public:
Point(int a, int b) : x(a), y(b)
{
std::cout << "Constructing point (" << a << ", " << b << ") "
<< std::endl;
}
Point(const Point& p) : x(p.x), y(p.y)
{
std::cout << "In copy constructor " << p.x << " " << p.y
<< std::endl;
}
Point& operator=(const Point& p)
{
std::cout << "In assignment operator " << p.x << " " << p.y
<< std::endl;
x = p.x;
y = p.y;
return *this;
}
};
int main()
{
Point p1 = Point(1, 2);
return 0;
}
現在,當我執行此我看到的是Constructing point (1, 2)
。我假設編譯器在這裏做一些優化。從理論上來說,臨時構造是否正確,然後調用賦值運算符來初始化p1?
確定這是有道理的 - 我想'點P2 = P1;',它被稱爲拷貝構造函數爲好,所以我沒有完全脫離標準,歡呼! – 2011-04-08 04:33:44