最近在B站看C++ 课程,发现复制构造函数调用举例 跟自己的调试不一样。以下是代码。
#include <iostream>
using namespace std;
class Point{
public:
Point();
Point(const Point &obj);
void getPosition();
private:
int x,y;
};
Point::Point(){
cout<<"Calling Constructor "<<endl;
}
Point::Point(const Point &p){
x = p.x;
y = p.y;
cout<<"Calling Copy Constructor "<<endl;
}
void Point::getPosition(){
cout<<"x "<<x<<" y "<<y<<endl;
}
void fun1(Point p);
Point fun2();
int main(){
Point a;
a.getPosition();
cout<<"\n"<<endl;
Point c;
c.getPosition();
cout<<"\n"<<endl;
Point b(a);
b.getPosition();
cout<<"\n"<<endl;
fun1(b);
cout<<"\n"<<endl;
b = fun2();
b.getPosition();
return 0;
}
void fun1(Point p){
cout<<"Calling fun1 begin"<<endl;
p.getPosition();
cout<<"Calling fun1 end"<<endl;
}
Point fun2(){
cout<<"Calling fun2 begin"<<endl;
Point b;
cout<<"Calling fun2 end"<<endl;
return b;
}
下边是打印结果
Calling Constructor
x -400344992 y 32766
Calling Constructor
x 0 y 0
Calling Copying Constructor
x -400344992 y 32766
Calling Copying Constructor
Calling fun1 begin
x -400344992 y 32766
Calling fun1 end
Calling fun2 begin
Calling Constructor
Calling fun2 end
x 0 y 0
B站的视频说在调用fun2()
的时候也会发生复制,但是结果里并没有发生。
是我弄错了?
另一个疑问就是:Point a
跟 Point c
初始化顺序不一样,x,y
的值也不一样?