我已经宣布了一个像这样的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 :(得分: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;
}
答案 1 :(得分:0)
在第一个程序中
int main(){
Point p1,p2;
p2=p1;
^^^^^
隐式地称为编译器创建的复制赋值运算符。 在此程序中,已使用默认构造函数
创建了对象p2
Point p1,p2;
第二个程序
int main(){
Point p1;
Point p2=p1;
^^^^^^^^^^^
确实称为复制构造函数。
答案 2 :(得分:0)
Point p1,p2;
p2=p1;
p2已经构造,因此第二个语句调用赋值运算符
点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