c++ - 运算符重载 C++ 中的友元函数与成员函数

标签 c++ operator-overloading friend-function

之前,我学习了如何将 C++ 中的运算符重载为类的成员函数和友元函数。虽然,我知道如何使用这两种技术在 C++ 中重载运算符。但我仍然很困惑**哪个更好**?重载运算符的成员函数或友元函数,我应该使用哪个,为什么? 请指导我!非常感谢您的回复。我将很高兴并感谢您的回答。

最佳答案

选择不是“成员(member)或 friend ”,而是“成员(member)或非成员(member)”。
(友元经常被过度使用,而且通常在学校过早地教授。)

这是因为您总是可以添加一个自由函数可以调用的公共(public)成员函数。

例如:

class A
{
public:
    explicit A(int y) : x(y) {}
    A plus(const A& y) const { return A{x + y.x}; }
private:
    int x;
};

A operator+(const A& lhs, const A& rhs) { return lhs.plus(rhs); }

至于如何选择:如果运算符不是类的实例作为左操作数,必须是自由函数,否则就看个人了品味(或者编码标准,如果你不是一个人的话)。

例子:

// Can't be a member because the int is on the left.
A operator+ (int x, const A& a) { return A{x} + a; }

对于具有相应变异运算符的运算符(如 ++=),通常将变异运算符作为成员,将另一个作为非成员成员:

class B
{
public:
    explicit B(int y) : x(y) {}
    B& operator+= (const B& y) { x += y.x; return *this; }
private:
    int x;
};

B operator+(B lhs, const B& rhs) { return lhs += rhs; }

当然你也可以拼写出来:

class C
{
public:
    explicit C(int y) : x(y) {}
    C& add(const C& y) { x += y.x; return *this; }
private:
    int x;
};

C& operator+=(C& lhs, const C& rhs) { return lhs.add(rhs); }
C operator+(C lhs, const C& rhs) { return lhs += rhs; }

关于c++ - 运算符重载 C++ 中的友元函数与成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43089272/

相关文章:

python - [咖啡] : Check failed: ShapeEquals(proto) shape mismatch (reshape not set)

c++ - Qt:如何让mainWindow在centralwidget调整大小时自动调整大小?

c++错误C2662无法将 'this'指针从 'const Type'转换为 'Type &'

c++ - 模板类的模板友元函数

c++ - 使用 CRTP 访问派生类的 protected 成员

c++ - 当>>运算符试图输入一个大于变量可以包含的值时,会发生什么?

c++ - 需要更好地理解带有 Windows API 的智能指针

c++ - 多个输出运算符?

c++ - 这个运算符重载函数返回什么?

c++ - 如何定义模板类模板友元函数,其参数之一是模板类主体之外的依赖名称?