c++ - 运算符重载 : cannot add two pointers

标签 c++ pointers reference operator-overloading fractions

我创建了一个 Fraction 类,它具有在两个 Fraction 对象之间进行加、减、乘和除的成员函数,以及所需的默认构造函数和复制构造函数。

对于这个问题,我必须使用指针(不能使用 vector !),因为分数对象只有在用户选择时才能创建。简而言之,指针声明和新初始化在不同的范围内。

我还尝试重载 operator=、operator+、operator-、operator* 和 operator/以接受如下内容。

Fraction* fr1 = new Fraction(1,2);

Fraction* fr2 = new Fraction(3,4);

Fraction* fr3 = new Fraction();

fr3 = fr1 + fr2;

我当前重载的 operator= 成员函数如下所示:

    Fraction* Fraction::operator=(const Fraction*& fr) {


      num = fr->num;

      denom = fr->denom;

      return this; 
    }

    Fraction* Fraction::operator+(const Fraction*& fr) const {

      int gcd = gcdRecurEuclid(num * fr->denom + denom * fr->num, denom * fr->denom);

      Fraction* temp;

      temp = new Fraction((num * fr->denom + fr->num * denom) / gcd, 

                          (denom * fr->denom) / gcd);

      return temp;
    }

我不断收到错误“+”:无法添加两个指针,这很可能意味着我的重载运算符 + 未正确编写(和/或我的重载赋值运算符)。 我需要做什么来纠正这个问题?再一次,我的导师希望我在指导下工作,不希望我通过或返回任何东西的拷贝。我要么需要通过引用(或指针?类似的东西?)。

最佳答案

如您所见,尝试对指针使用算术运算符将导致编译器尝试进行指针算术运算。要在指针上调用您自己的重载运算符,您可以这样做

Fraction *f, *g; // allocated with new
f->operator+(*g); /// Urgh!

或者,几乎一样丑

Fraction *f, *g;
(*f) + (*g);

使它更好一点的一种简单方法是像这样声明三个新的引用变量:

Fraction& f1 = *pfr1;
Fraction& f2 = *pfr2;
Fraction& f3 = *ptr3;

pfrN 是指向分数的指针。现在,如果您使用引用变量,您的重载运算符将被正确调用,并且您不需要放入所有额外的星号。引用将在范围的末尾消失,并且可能不会在您的程序中使用任何额外的内存。不过,您仍然需要删除原始指针!

关于c++ - 运算符重载 : cannot add two pointers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19850991/

相关文章:

c++ - Ref 限定的成员函数设计打破了 const 右值

c++ - Int& 到 const int -static 与 dynamic-

pointers - 将引用的内部结构字段与go中的字符串类型进行比较

C++ 将 wstringstream 传递给另一个函数

c - "error: subscripted value is neither array nor pointer nor vector",但为什么呢?

c - C 中的字符串指针覆盖现有指针

delphi - Delphi 中 CONTAINING_RECORD C 宏的等效函数是什么?

c++ - 如何实例化成员函数指针?

c++ - 使用 void 指针时转换函数(CUBA Nint 例程)

c++ - 错误 : *** glibc detected *** w5: double free or corruption (fasttop):