成员赋值笛卡尔类 c++

Memberwise assignment cartesian class c++

本文关键字:c++ 笛卡尔 赋值 成员      更新时间:2023-10-16

我有一个笛卡尔类的代码,现在我想添加一个成员赋值来将 coord1 的值设置为 coord2。我不太确定如何做到这一点。为类对象编写成员赋值的语法是什么?我会对类本身进行更改,还是将它们放在主函数中?

#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;
}

简单的方式执行此操作:通过使用struct并省略访问说明符,使所有成员public。无论如何,如果您提供完全访问权限,则数据隐藏没有意义。

此外,您可以

省略所有自定义构造函数,因为您可以一次分配所有成员而无需。

只需将 get 和 set 方法添加到您的类中即可

void Cartesian::SetX(double new_x)
{
    x = new_x;
}

double Cartesian::GetX()
{
    return x;
}

以及用于GetY()SetY(double y)的类似功能。这将使您能够在需要时访问和设置xy的值,以达到您想要的任何内容。

或者,只需将这些成员上的访问说明符更改为 public 而不是 private

另外,请注意,您的类有一个默认operator=(),如果将Cartesian的一个实例分配给另一个实例,则该将按成员复制成员。

因此,如果您有

 Cartesian point1(1.0,2.0);
 Cartesian point2(4.5,4.3);

您只需将point1分配给point2

 point2 = point1;