简体   繁体   English

在不使用成员函数和友元函数的情况下实现运算符重载

[英]Achieve operator overloading without using member functions and friend functions

Is it possible for a non-member and non-friend function to achieve this?非会员和非朋友 function 是否有可能实现这一目标?

Presume that it is a binary operator, which means we need to pass two arguments from different objects.假设它是一个二元运算符,这意味着我们需要从不同的对象传递两个 arguments。 How can it access the private members?它如何访问私有成员?

This is an example:这是一个例子:

class Foo{
private:
    int m_i;
public:
    Foo(int i): m_i{i} {}
    int get() { return m_i; }
};

Foo operator+(Foo& foo1, Foo& foo2){
    return {foo1.get() + foo2.get()}; // you can not access m_i directly as you do in member functions and friend functions
}

Generally speaking, you use normal functions for operator overloading operators that don't modify the state left operand and don't need access to private or protected members directly.一般来说,对于不修改 state 左操作数并且不需要直接访问私有或受保护成员的运算符重载运算符,您可以使用普通函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM