gpt4 book ai didi

c++ - 使用友元函数重载算术运算符

转载 作者:行者123 更新时间:2023-12-02 01:26:44 26 4
gpt4 key购买 nike

我找到了如何重载算术运算符的示例 using friend functions ,并且重载运算符函数在类内部定义,并带有注释:

/* This function is not considered a member of the class, even though the definition is 
inside the class */

这是示例:

#include <iostream>

class Cents
{
private:
int m_cents {};

public:
Cents(int cents) : m_cents{ cents } { }

// add Cents + Cents using a friend function
// This function is not considered a member of the class, even though the definition is inside the class
friend Cents operator+(const Cents& c1, const Cents& c2)
{
// use the Cents constructor and operator+(int, int)
// we can access m_cents directly because this is a friend function
return Cents{c1.m_cents + c2.m_cents};
}

int getCents() const { return m_cents; }
};

int main()
{
Cents cents1{ 6 };
Cents cents2{ 8 };
Cents centsSum{ cents1 + cents2 };
std::cout << "I have " << centsSum.getCents() << " cents.\n";

return 0;
}

这个函数真的不是该类的成员吗?并且都是在类内部定义的友元函数,但不是该类的成员,或者它仅适用于使用friend关键字的重载函数。

最佳答案

Is this function really not a member of that class?

是的。

and are all friend functions defined inside the class but not a member of that class

是的。

简单来说,你不是你的 friend 。你的 friend 可能可以访问你的所有东西(访问类成员),并且住在你的房子里(在类体内定义),但他们仍然不是你(类的成员)。它们与类是分离的,唯一的耦合是它们可以访问类成员。

关于c++ - 使用友元函数重载算术运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74432989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com