【发布时间】:2017-02-09 03:02:27
【问题描述】:
我有一个代表特殊数字的类。
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); 并且它工作正常。
我有哪些选择?如果我有一个像
这样的公共方法const *unsigned int getData() const; 我认为即使那样它实际上并没有使变量返回const 对吗?我真的不希望有 getData() 方法,而只是将具有访问权限的函数声明为 friend。
【问题讨论】:
-
您将
operator+声明为成员函数,因此它可以访问data,不是吗? -
~~它无法访问
other的数据,这使我无法进行算术运算。~~ -
旁注:即使您坚持使用成员函数进行重载,也没有理由按值接受参数。
const SecretInteger& other肯定是你想要的。 -
@ShadowRanger 为什么让运算符重载成员函数是不好的?有什么选择?如果你的意思是建立一个朋友功能,它不允许我这样做。
SecretInteger也是一个不可变的类,所以我认为按值传递是完全可以的,因为我不打算在任何时候对other进行任何更改。 -
@Hatefiend 不,可以。你试过了吗?