c++ - 为运算符方法编写实现

标签 c++ header operator-overloading add long-integer

所以我有一个 LongInt 类,它将对 + 和 * 运算符进行新定义。头文件中的初始化如下所示:

friend LongInt operator+(const LongInt& x, const LongInt& y);
friend LongInt operator*(const LongInt& x, const LongInt& y);

但是在我的实现文件中,我定义了 header 中的方法,VS 无法识别 header 中列出的 operator+ 函数或 operator* 函数。我正在使用代码:

friend LongInt LongInt::operator+(const LongInt& x, const LongInt& y)
{

}

friend LongInt LongInt::operator*(const LongInt& x, const LongInt& y)
{

}

关于为什么当我尝试定义运算符时此代码不起作用的任何想法?

最佳答案

friend 关键字仅在类内声明或定义运算符时使用;当在类中将运算符声明为 friend 并在其他地方定义它时,friend 仅用于声明,而不用于定义。此外,在类中声明为 friend 的函数实际上是命名空间范围内的自由函数,而不是类成员。因此,您的定义应该更像是:

LongInt operator +(LongInt const& x, LongInt const& y) { /*...*/ }
LongInt operator *(LongInt const& x, LongInt const& y) { /*...*/ }

要进一步阅读 Material ,请阅读以下页面:C++ FAQ: Friends

关于c++ - 为运算符方法编写实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5560464/

相关文章:

CSS 标题样式

c++ - 为什么operator()具有奇怪的行为?

c++ - 派生类的重载 << 运算符表示无效操作数

c++ - 统一哈希函数

c++ - 在 LLVM 中获取非常量操作数

css - 这被认为是草率的方式吗?

c++ - 使用accumulate时,C++中的operator+不匹配

c++ - 如何以编程方式检查 Windows Server 2016 上是否安装了桌面体验

c++ - 为嵌套类型定义哈希模板

pdf - iTextSharp - 所有页面的页眉和页脚