对称二进制运算符

对称二进制运算符

本文介绍了具有不同类型的C ++对称二进制运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在学习C ++,我想知道我是否可以深入了解创建可在两种不同类型的实例上工作的二进制运算符的首选方式.这是我用来说明我的担忧的示例:

I am learning C++ and I was wondering if I could gain some insight into the preferred way of creating binary operators that work on instances of two different types. Here is an example that I've made to illustrate my concerns:

class A;
class B;

class A
{
    private:
        int x;

    public:
        A(int x);

        int getX() const;

        int operator + (const B& b);
};


class B
{
    private:
        int x;

    public:
        B(int x);

        int getX() const;

        int operator + (const A& A);
};


A::A(int x) : x(x) {}

int A::getX() const { return x; }

// Method 1
int A::operator + (const B& b) { return getX() + b.getX(); }


B::B(int x) : x(x) {}

int B::getX() const { return x; }

// Method 1
int B::operator + (const A& a) { return getX() + a.getX(); }


// Method 2
int operator + (const A& a, const B& b) { return a.getX() + b.getX(); }

int operator + (const B& b, const A& a) { return a.getX() + b.getX(); }


#include <iostream>

using namespace std;

int main()
{
    A a(2);
    B b(2);

    cout << a + b << endl;

    return 0;
};

如果我想使两种类型之间具有对称性,那么哪种方法是上述代码中最好的方法.选择一种方法而不是另一种方法是否有任何危险?这是否与返回类型有所不同?请解释!谢谢!

If I would like to have symmetry among the two types, which method is the best approach in the above code. Are there any possible dangers in choosing one method over the other? Does this vary with the return type? Please explain! Thank you!

推荐答案

最好的方法是定义(在任何一个类之外)int operator+ (const A& a, const B& b),并在需要时使其成为两个类的友好函数.另外,定义

The best way is to define (outside of either class) int operator+ (const A& a, const B& b), and make it a friend function of both classes if needed. In addition, define

int operator+(const B& b, const A& a) {return a + b;}

使其对称.

这篇关于具有不同类型的C ++对称二进制运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 08:46