运算符重载'+' C++ 中的运算符

发布于 2024-09-18 00:53:56 字数 369 浏览 5 评论 0原文

我遇到以下在 Visual Studio 2008 上运行的代码的问题。当您有如下要重载的语句时,如何编写 operator + 的函数定义?

class Distance
{
    private:
        int feet,inches;
};

main......

Distance Obj, Obj1(2, 2);

Obj = 3 + Obj1; // This line here

Obj1+3 很简单,但是这个编译器如何知道它必须进行重载?

假设我必须将值 3 添加到 Obj1 的数据成员 feet 中。

I am facing a problem with the code below which is run on Visual Studio 2008. How do I write the function definition for operator + when you have a statement to be overloaded as follows?

class Distance
{
    private:
        int feet,inches;
};

main......

Distance Obj, Obj1(2, 2);

Obj = 3 + Obj1; // This line here

Obj1+3 is easy, but how does this one compiler know that it has to do overloading?

Suppose I have to add the value 3 to the data member feet of Obj1.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

堇年纸鸢 2024-09-25 00:53:56

现在有几个答案建议使用非成员operator+重载来允许“添加”Distanceint对象。这实际上没有意义:将有单位的 Distance 添加到没有单位的 int 意味着什么?

但是,将两个 Distance 对象添加在一起确实有意义。如果您的距离为两英尺,再加上三英尺的距离,您将得到五英尺的距离。这是有道理的。

您可以通过在两个 Distance 对象之间重载 operator+ 来实现此目的(为简单起见,我假设您的 Distance 只有一个包含英寸的字段在实际应用程序中,您不希望使用单独的英寸和英尺字段,您可能希望使用 SI 单位,例如米,但这取决于应用程序并且完全取决于您):

Distance operator+(const Distance& lhs, const Distance& rhs)
{
    return Distance(lhs.inches + rhs.inches);
}

但是,如果您希望能够按照以下方式执行某些操作,那么这对您没有帮助:

Distance d;
d = d + 42; // assume 42 has the same units as a Distance object has

为了使这一点有意义,您可以使用转换构造函数:

struct Distance
{
    Distance(int in = 0) : inches(in) { }
private:
    int inches;
};

这里的构造函数是转换构造函数,因为它不是 < code>explicit 并且可以使用单个参数调用。它允许将单个 int(或可隐式转换为 int 的值)转换为 Distance 对象。这允许您编写

Distance d;
d = d + 42;

为什么这与使用采用 Distanceint 参数的 operator+ 重载不同?简单:它强制在加法之前进行从 intDistance 的转换,因此实际的加法不必关心其操作数:它只是将两个距离相加一起并让 Distance 构造函数处理需要发生的任何转换。

Several answers now suggest using a non-member operator+ overload to allow "addition" of Distance and int objects. This doesn't really make sense: what does it mean to add a Distance, which has a unit, to an int, which does not?

However, it does make sense to add two Distance objects together. If you have one distance of two feet and add another distance of three feet to it, you get a distance of five feet. This makes sense.

You can accomplish this by overloading operator+ between two Distance objects (for simplicity, I've assumed that your Distance only has a single field containing inches. In a real-world application, you wouldn't want to have separate fields for inches and feet. You'd probably want to use an SI unit, like meters, but that depends on the application and is entirely up to you):

Distance operator+(const Distance& lhs, const Distance& rhs)
{
    return Distance(lhs.inches + rhs.inches);
}

This doesn't help you, though, if you want to be able to do something along the lines of

Distance d;
d = d + 42; // assume 42 has the same units as a Distance object has

In order to get this to make sense, you can use a converting constructor:

struct Distance
{
    Distance(int in = 0) : inches(in) { }
private:
    int inches;
};

The constructor here is a converting constructor because it is not explicit and can be called with a single argument. It allows a single int (or a value that is implicitly convertible to an int) to be converted to a Distance object. This allows you to write

Distance d;
d = d + 42;

Why is this different from using an operator+ overload that takes a Distance and an int argument? Simple: it forces the conversion from int to Distance to take place before the addition, so the actual addition doesn't have to care about its operands: it simply adds two distances together and lets the Distance constructors deal with any conversions that need to take place.

笑咖 2024-09-25 00:53:56

您需要编写一个自由函数(在 class 之外):

Distance operator+(int lhs, const Distance& rhs)
{
  return ...;
}

如果 ... 需要使用 Distance 的私有成员,则将其设为友元在距离中。

class Distance
{
  ...
  friend Distance operator+(int lhs, const Distance& rhs);
};

最后,如果您希望能够在左侧使用 +Distance,只需像上面那样定义另一个 operator+ 重载,但使用距离作为第一个参数。

综上所述,我会避免做你看起来正在做的事情。作为 Distance 类的用户,我不知道您所做的操作是否会增加 3 英尺、3 英寸或 3 米。如果您不打算使用 SI 单位(米),则不应允许添加非 Distance 值。

You need to write a free function (outside the class):

Distance operator+(int lhs, const Distance& rhs)
{
  return ...;
}

If ... needs to use private members of Distance then make it a friend in Distance.

class Distance
{
  ...
  friend Distance operator+(int lhs, const Distance& rhs);
};

Finally, if you want to be able to + with Distance on the left-hand side, just define another operator+ overload as above, but with Distance as the first argument.

All this said, I would avoid doing what you appear to be doing. As a user of your Distance class, I don't know whether what you are doing would add 3 feet, 3 inches, or 3 meters. If you aren't going to use SI units (meters) then you shouldn't allow addition with non-Distance values.

浪漫之都 2024-09-25 00:53:56

除了重载带有两个 Distance 对象的 + 运算符之外,您还应该避免重载 operator+(const Distance &, int) 正如其他答案中所指出的。最好定义一些常量,例如:

const Distance feet(1,0);
const Distance inch(0,1);

,并重载运算符*(int, const Distance &),以便您可以编写:,

Distance dist = 3 * feet + 5 * inch;
Distance dist2 = dist + 2 * feet;

这更具可读性。

Apart from overloading the + operator taking two Distance objects you should avoid overloading operator+(const Distance &, int) as pointed out in other answers. It's better to define some constants like:

const Distance feet(1,0);
const Distance inch(0,1);

and also overload the operator*(int, const Distance &) so that you then can write:

Distance dist = 3 * feet + 5 * inch;
Distance dist2 = dist + 2 * feet;

which is more readable.

日久见人心 2024-09-25 00:53:56

一般来说,这种形式的运算符将被声明为:

Distance operator+(int lhs, const Distance& rhs) {
  // Assuming the int value represents feet
  return Distance(rhs.feet + lhs, rhs.inches);
}

您可能还想定义对称:

Distance operator+(const Distance& lhs, int rhs) {
  // Assuming the int value represents feet
  return Distance(lhs.feet + rhs, lhs.inches);
}

另外,我建议您听取 James McNellis 的建议 - 如果您只有一个成员代表 a 中的长度,您的工作将会简化单个单元。

Generally an operator of that form would be declared as:

Distance operator+(int lhs, const Distance& rhs) {
  // Assuming the int value represents feet
  return Distance(rhs.feet + lhs, rhs.inches);
}

You'd probably also want to define the symmetric:

Distance operator+(const Distance& lhs, int rhs) {
  // Assuming the int value represents feet
  return Distance(lhs.feet + rhs, lhs.inches);
}

Also, I suggest you heed the advice of James McNellis--your job will be simplified if you just have one member representing lengths in a single unit.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文