类型的无效操作数 - C++ [英] invalid operands of types - c++

查看:66
本文介绍了类型的无效操作数 - C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C++ 代码中有一个名为 ThreeDigits 的类.我以这种方式重载了 + 操作数:

I have a class named ThreeDigits on c++ code. I overloaded the + operand, this way:

ThreeDigits* ThreeDigits::operator+(const ThreeDigits &number) const

{
   double result= getNumber()+number.getNumber();
   ThreeDigits* new_result=new ThreeDigits(result);
   return new_result;
}

但是当我写在主函数上时:

but when I write on the main function:

    ThreeDigits* first=new ThreeDigits(2.55998);
    ThreeDigits* second=new ThreeDigits(5.666542);
    ThreeDigits* result=first+second;

我收到以下编译错误:ThreeDigits* 和 ThreeDigits* 类型的无效操作数转换为二元运算符 +

I get the following compilation error: invalid operands of types ThreeDigits* and ThreeDigits* to binary operator+

你能告诉我有什么问题吗?谢谢

Can you tell me what is the problem? thanks

推荐答案

您正在尝试对指向对象的指针而不是对象本身求和.要调用重载运算符,您必须在对象上调用它,从而取消对指针的引用.

You are trying to sum pointers to objects instead of the objects themselves. To invoke the overloaded operator you must call it on objects, thus dereferencing the pointers.

顺便说一句,用 new 创建所有这些对象是一种糟糕的 C++ 方式;在 C++ 中,与 Java/C# 不同,您应该仅在必要时使用 new,并在堆栈上分配所有其余部分.让 operator+ 返回一个指向新创建对象的指针是令人厌恶的.

By the way, creating all those objects with new a terrible way to do C++; in C++, unlike Java/C#, you should use new only when you have to, and allocate all the rest on the stack. Having the operator+ return a pointer to a newly created object is an abomination.

编写代码的 C++ 方式是:

The C++ way of writing your code would be:

ThreeDigits ThreeDigits::operator+(const ThreeDigits &number) const
{
   return ThreeDigits(getNumber()+number.getNumber()); // construct a temporary and return it
}

// ...

ThreeDigits first(2.55998);
ThreeDigits second(5.666542);
ThreeDigits result=first+second;

顺便说一下,重载算术运算符的常用方法是首先重载赋值版本(+=、-=、...),然后在它们之上构建正常"版本.有关运算符重载的详细信息,请参阅运算符重载常见问题解答.

By the way, the usual way of overloading arithmetic operators is first overloading the assigning versions (+=, -=, ...) and then build the "normal" version over them. For more info about operator overloading see the operator overloading FAQ.

这篇关于类型的无效操作数 - C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆