编写运算符方法的实现

发布于 2024-10-30 06:59:13 字数 571 浏览 4 评论 0原文

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

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

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

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

}

并且

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

}

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

So I have a LongInt class that will have new definition for the + and * operators. The initialization in the header file looks like:

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

however in my implementation file, where I'm defining the methods found in the header, VS doesn't recognize the operator+ function or the operator* function as being listed in the header. I'm using the code:

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

}

and

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

}

Any ideas as to why this code wont work when I'm trying to define the operators?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

檐上三寸雪 2024-11-06 06:59:13

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

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

如需进一步阅读材料,请阅读以下页面:C++ 常见问题解答:朋友< /a>

The friend keyword is only used when declaring or defining the operator inside of a class; when declaring the operator as a friend inside of the class and defining it elsewhere, friend is only used on the declaration, not the definition. Also, functions declared as friend inside a class are in fact free functions in namespace scope, not class members. So, your definitions should look more like:

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

For further reading material, read over the following page: C++ FAQ: Friends

池木 2024-11-06 06:59:13

您正在重写运算符...您使用运算符“调用”它:

LongInt foo;
LongInt bar;
LongInt foobar = foo + bar;

You're overriding an operator ... you "call" it using the operator:

LongInt foo;
LongInt bar;
LongInt foobar = foo + bar;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文