【发布时间】:2020-05-25 16:38:51
【问题描述】:
#include <iostream>
class Point {
private:
int* x; int y;
public:
Point(int x1, int y1) {
int* x = new int;
*x = x1 ;
y = y1;
}
int* getX() { return x; }
void setX(int* p) { x = p; }
int getY() { return y; }
};
int main()
{
Point* p1 = new Point(10, 15);
Point* p2 = new Point(20, 25);
p2->setX(p1->getX());
std::cout << "p1.x = " << p1->getX() << ", p1.y = " << p1->getY() << std::endl;
std::cout << "p2.x = " << p2->getX() << ", p2.y = " << p2->getY() << std::endl;
delete p1;
delete p2;
return 0;
}
构造函数中分配空间有什么问题?
【问题讨论】:
-
我无法打印 POINT X 值
-
代码没有解释它应该做什么只是做了它所做的。我们怎么知道你还期望它做什么?
-
@user3865070 您正在两个
points 中打印x变量的地址。您的意思是打印*p1->getX()吗? (这可能会使您的代码崩溃,如下面的回答中所述) -
顺便说一句,如果你无缘无故停止使用指针,你的大部分问题都会消失
标签: c++ class memory-management destructor definition