【发布时间】:2016-01-28 10:58:15
【问题描述】:
任务是在上面的代码中编写计算新点的成员函数,即另外两个点的数量。而且我不知道如何返回对象或我应该做什么。这里是代码,函数标有三个!!!。函数必须返回一些东西,我不能让它为 void,因为对 void 的引用是不允许的。
class point {
private:
float x;
float y;
public:
point();
point(float xcoord, float ycoord);
void print();
float dist(point p1, point p2);
!!! float &add(point p1, point p2);
float &X();
float &Y();
~point();
};
float & point::X() { return x; }
float & point::Y() { return y; }
point::point() {
cout << "Creating POINT (0,0)" << endl;
x = y = 0.0;
}
point::point(float xcoord, float ycoord) {
cout << "Creating POINt (" << xcoord << "," << ycoord << ")" << endl;
x = xcoord;
y = ycoord;
}
void point::print() {
cout << "POINT (" << x << "," << y << ")";
}
float point::dist(point p1, point p2) {
return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));
}
!!!// float & point::add(point p1, point p2) {
point z;
z.X() = p1.X() + p2.X();
z.Y() = p1.Y() + p2.Y();
z.print();
}
point::~point() {
cout << "Deleting ";
print();
cout << endl;
}
int main() {
point a(3, 4), b(10, 4);
cout << "Distance between"; a.print();
cout << " and "; b.print();
cout << " is " << a.dist(a, b) << endl;
}
我成功了!这是必须添加的功能
//prototype
point &add(point& p1, point& p2);
//function itself
point & point::add(point& p1, point& p2) {
point z;
z.x = p1.X() + p2.X();
z.y = p1.Y() + p2.Y();
z.print();
return z;
}
非常感谢 ForceBru!和你们所有人
【问题讨论】:
-
如果你添加两个
point,你很可能想要返回一个point,不是吗? -
不清楚你的问题是什么,如果你想从成员函数中返回一个对象,就这样做吧....
-
并且顺便说一句,返回对私有成员的引用会破坏封装,这样您也可以将成员公开。我建议要么从一开始就将它们公开,要么从 getter 中返回值
-
@tobi303 是对的,尝试声明点 add(point x, pointy);然后在方法中result = new point();....返回结果
-
不要返回对
add函数内的对象的引用。