2012-11-20 42 views
8

假设我定义这个结构:运算符重载在结构

struct Point { 
    double x, y; 
}; 

我怎样才能重载+操作,这样,申报,

Point a, b, c; 
double k; 

表达

c = a + b; 

产量

c.x = a.x + b.x; 
c.y = a.y + b.y; 

和表达

c = a + k; 

产生

c.x = a.x + k; 
c.y = a.y + k; // ? 

是否适用于后者的情况下可交换的属性保持?也就是说,c = a + k;c = k + a;必须分开处理吗?

回答

13

只要做到这一点:

Point operator+(Point const& lhs, Point const& rhs); 
Point operator+(Point const& lhs, double rhs); 
Point operator+(double lhs, Point const& rhs); 

至于你的最后一个问题,编译器可以进行没有 假设关于您的运营商做什么。 (请记住,std::string上的 +运算符是而不是可交换。)因此,您的 必须同时提供重载。

或者,可以(通过具有 Point一转换构造函数)提供的 doublePoint的隐式转换。在这种情况下,上述第一次超载将处理 所有三种情况。

+3

+1对于耐克的态度 – fredoverflow

+0

为什么我们必须将Point参数声明为常量? – Raptor

+1

@JosuéMolina所以你可以通过临时工给他们;你不能用临时的初始化非const引用。鉴于'Point'的简单性,通过值直接传递它们没有问题,而不是通过引用(在这种情况下,它们是否是'const'或不是无关紧要的)。但是无处不在的约定是通过引用const来传递类的类型,当约定真正无处不在时,并且不会导致其他问题时,最好遵守它们,如果只是为了让人们不要问你为什么要这样做不同。 –

4

在C++中,结构和类之间只有一个区别:在结构中,默认可见性是公共的,而在类中是私有的。

除此之外,你可以在结构中的类中做任何事情,它看起来完全一样。

将运算符重载在结构体中,就像在类中一样。

+1

我不认为提问者知道如何将一个类来完成。 –

4

这是我该怎么做的。

struct Point { 
    double x, y; 
    struct Point& operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; return *this; } 
    struct Point& operator+=(const double& k) { x += k; y += k; return *this; } 
}; 

Point operator+(Point lhs, const Point& rhs) { return lhs += rhs; } 
Point operator+(Point lhs, const double k) { return lhs += k; } 
Point operator+(const double k, Point rhs) { return rhs += k; } 
3

这也将工作:

struct Point{ 
    double x,y; 
    Point& operator+(const Point& rhs){ 
      x += rhs.x; 
      y += rhs.y; 
      return *this; 
    } 
}