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

标签 c++ class operator-overloading friend function-definition

我找到了如何重载算术运算符的示例 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/

相关文章:

c# - 多重继承?

c++ - 使用仿函数改变大小写

c++ - 如何在线程中使用 v8?

c++ - 找到字符串模式的更好解决方案?

c++ - 如何找出为什么我的程序一直有无限循环?

java - java中如何绑定(bind)两个类?

html - 如何在 Bootstrap 中获取跨越父级整个宽度的按钮组?

c++ - C++ 错误中的 Operator() 重载和继承

operator-overloading - Coq 符号中的重载运算符

c++ - 从给定位置开始的简单链表中删除元素