0

我正在尝试添加它们在同一类中的两个对象。

在班级的私人部分,我有两个int变量

class One {

private:
int num1, num2;
public:

    One operator+=(const One&); // - a member operator that adds another One object - to the current object and returns a copy of the current object
    friend bool operator==(const One&, const One&); // - a friend operator that compares two One class objects for equality
};

 One operator+(const One&, const One&);// - a non-friend helper operator that adds One objects without changing their values and returns a copy of the resulting One 

我不确定opeartor+我猜有什么问题

One operator+(const One &a, const One &b){

One c,d,r;

c = a;
d = b;

r += b;
r += a;

return r;
}

我认为上面的代码是错误的,但我尝试像 b.num1 一样使用,我得到编译错误

error: 'int One::num1' is private error: within this context

而且我也不能使用 b->num1 因为上面的函数不在成员函数部分。

error: base operand of '->' has non-pointer type 'const One'

这就是它的调用方式main

Result = LeftObject + RightObject;

4

2 回答 2

5

如果你已经实现了这个成员函数:

One One::operator+=(const One&);

然后你可以这样实现非成员加法运算符:

One operator+(const One& lhs, const One& rhs) {
  One result = lhs;
  result += rhs;
  return result;
}

这可以稍微简化为以下内容:

One operator+(One lhs, const One& rhs) {
  return lhs += rhs;
}

此模式(您可以适应所有运算符/运算符-赋值对)将运算符-赋值版本声明为成员——它可以访问私有成员。它将操作符版本声明为非朋友非成员——这允许在操作符的任一侧进行类型提升。

旁白:该+=方法应返回对 的引用*this,而不是副本。所以它的声明应该是:One& operator+(const One&).


编辑:下面是一个工作示例程序。

#include <iostream>
class One {
private:
  int num1, num2;

public:
  One(int num1, int num2) : num1(num1), num2(num2) {}
  One& operator += (const One&);
  friend bool operator==(const One&, const One&);
  friend std::ostream& operator<<(std::ostream&, const One&);
};

std::ostream&
operator<<(std::ostream& os, const One& rhs) {
  return os << "(" << rhs.num1 << "@" << rhs.num2 << ")";
}

One& One::operator+=(const One& rhs) {
  num1 += rhs.num1;
  num2 += rhs.num2;
  return *this;
}

One operator+(One lhs, const One &rhs)
{
  return lhs+=rhs;
}

int main () {
  One x(1,2), z(3,4);
  std::cout << x << " + " << z << " => " << (x+z) << "\n";
}
于 2012-06-27T15:34:27.243 回答
1

我不明白为什么operator+是错误的:

#include <stdio.h>

class One {
    public:
        One(int n1, int n2): num1(n1),num2(n2) {}

    private:
        int num1, num2;
    public:
        One operator+=(const One& o) {
            num1 += o.num1;
            num2 += o.num2;
            return *this;
        }
        friend bool operator==(const One&, const One&); // - a friend operator that compares two One class objects for equality
        void print() {
            printf("%d,%d\n", num1, num2);
        }
};

One operator+(const One& a, const One& b) {
    One r(0,0);
    r += b;
    r += a;
    return r;
}

int main() {
    One a(1,2),b(3,4);
    One r = a + b;
    r.print();
}
于 2012-06-27T15:34:18.320 回答