#include
using namespace std;
class Point {
public:
Point(int a, int b);
Point(const Point& p);
void print()
{
cout << x << " " << y << endl;
}
private:
int x, y;
};
Point::Point(int a, int b)
{
x = a;
y = b;
cout << "Using normal constructor." << endl;
}
Point::Point(const Point& p)
{
x = 2 * p.x;
y = 2 * p.y;
cout << "Using copy constructor." << endl;
}
void fun1(Point p)
{
p.print();
}
Point fun2()
{
Point p4(10, 30);
return p4;
}
int main()
{
Point p1(30, 40);
p1.print();
Point p2(p1);
p2.print();
Point p3 = p1;
p3.print();
fun1(p1);
p2 = fun2();
p2.print();
return 0;
}
VS2019 里运行如图:
这个应该和编译器优化有关,不同编译器结果不同
不知道你这个问题是否已经解决, 如果还没有解决的话:很有可能是因为你的代码中没有正确实现拷贝构造函数,导致返回的临时对象没有按照你期望的方式进行拷贝。你可以添加以下代码实现拷贝构造函数:
class MyClass {
public:
int x, y;
// 默认构造函数
MyClass() {
x = y = 0;
}
// 拷贝构造函数
MyClass(const MyClass& other) {
x = other.x;
y = other.y;
std::cout << "Using copy constructor" << std::endl;
}
// 重载乘法操作符
MyClass operator*(int m) {
MyClass temp;
temp.x = x * m;
temp.y = y * m;
return temp;
}
};
int main() {
MyClass a;
a.x = 10;
a.y = 30;
MyClass b = a * 2;
std::cout << b.x << " " << b.y << std::endl;
return 0;
}
上述代码中,我们添加了一个拷贝构造函数来确保在返回对象时正确拷贝对象。此外,我们还在类中重载了乘法操作符以实现我们所期望的对象乘以2的效果。输出应该为“Using copy constructor”。
这样做能够解决你的问题,如果还有疑问或者代码无法正常运行,可以再发一条信息~