我有笛卡尔类的代码,现在我想添加一个成员赋值来将coord1的值设置为coord2。我不太清楚该怎么做。为类对象编写成员赋值的语法是什么?我会对类本身进行更改,还是将它们放在main函数中?
#include <iostream>
using namespace std;
class Cartesian
{
private:
double x;
double y;
public:
Cartesian( double a = 0, double b = 0) : x(a), y(b){}
friend istream& operator>>(istream&, Cartesian&);
friend ostream& operator<<(ostream&, const Cartesian&);
};
istream& operator>>(istream& in, Cartesian& num)
{
cin >> num.x >> num.y;
return in;
}
ostream& operator<<( ostream& out, const Cartesian& num)
{
cout << "(" << num.x << ", " << num.y << ")" << endl;
return out;
}
int main()
{
Cartesian coord1, coord2;
cout << "Please enter the first coordinates in the form x y" << endl;
cin >> coord1;
cout << "Please enter the second coordinates in the form x y" << endl;
cin >> coord2;
cout << coord1;
cout << coord2;
return 0;
}
答案 0 :(得分:2)
以简单的方式执行:使用public
并省略访问说明符,使所有成员struct
成为可能。如果你提供完全访问权限,数据隐藏没有意义。
此外,您可以省略所有自定义构造函数,因为您可以一次性分配所有成员。
答案 1 :(得分:1)
只需将get和set方法添加到您的类
即可void Cartesian::SetX(double new_x)
{
x = new_x;
}
和
double Cartesian::GetX()
{
return x;
}
以及GetY()
和SetY(double y)
的类似功能。这样,您就可以根据需要随时随地访问和设置x
和y
的值。
或者,只需将这些成员的访问说明符更改为public
而不是private
。
另外,请注意,如果您将operator=()
的一个实例分配给另一个实例,则您的类会有成员复制成员的默认Cartesian
。
因此,如果你有
Cartesian point1(1.0,2.0);
Cartesian point2(4.5,4.3);
您可以通过
简单地将point1
分配给point2
point2 = point1;