运算符重载函数作为朋友?

Operator overloaded functions as friend?

我有一个 class 代表一个特殊的数字。

class SecretInteger
{
private:
    unsigned int *data;
    size_t length;

public: 
    SecretInteger operator+(const SecretInteger other) const;
}

我不允许我的代码的任何其他部分访问 data 变量。但是,我的 operator+ 函数必须能够看到它。通常在这种情况下,我知道使用 friend 关键字是唯一的方法。但是当我写的时候:

friend SecretInteger operator+(const SecretInteger other);

它声称 operator+ 不能被声明为朋友,即使我之前写过 friend std::ostream& operator<<(std::ostream& stream, const SecretInteger val); 并且它工作正常。

我有哪些选择?如果我有一个 public 方法,比如

const *unsigned int getData() const; 我认为即便如此它实际上并没有使变量返回 const 对吗?我真的不想使用 getData() 方法,而只是将具有访问权限的函数声明为 friend.

你没有将成员函数声明为friendfriend是为了让non-member函数访问内部,以及operator+的单操作数重载是一个成员函数。

无论如何,如果你正确地实现了二元运算符,你根本就不需要交友。将 += 作为成员函数实现(不需要 friend,class 总是 "friends" 本身),然后实现 non-member +根据 += 的运算符,它使用 += 对内部结构的访问来避免整个友谊问题。

重载的基本规则can be found here应该会有很大帮助。