可交换运算符重载+ 2个不同的对象 [英] Commutative operator overloading + of 2 different objects

查看:136
本文介绍了可交换运算符重载+ 2个不同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个代表矩阵的类:
1. RegularMatrix-O(n ^ 2)表示形式
2. SparseMatrix-一个表示为链表(无零)的矩阵.

I have 2 classes which represent a matrix:
1. RegularMatrix - O(n^2) representation
2. SparseMatrix - a matrix that is represented as linked list (without zeros).

让我说:

RegularMatrix a;
SparseMatrix b;

我希望能够做到:

a+b;

,还有:

b+a;

所以我正在超载+运算符.我的问题是,由于我希望加法运算是可交换的(a + b = b + a),我是否需要实现2个重载,每种情况一个?

so i'm overloading the + operator. My question is, since I want the addition to be commutative (a+b = b+a), do i need to implement 2 overloadings, one for each case?

RegularMatrix operator+(const RegualarMatrix &, const SparseMatrix &);
RegularMatrix operator+(const SparseMatrix & ,const RegualarMatrix &);

还是编译器自行决定的一般形式?

or is there a general form which the compiler decides by itself?

谢谢

推荐答案

是的,您需要两个版本.但是,如果操作确实是可交换的,则可以将一个转发给另一个

Yes you need both versions. But you can forward the one to the other, if the operation really is commutative

RegularMatrix operator+(const SparseMatrix &a, const RegualarMatrix &b) {
    return b + a;
}

这篇关于可交换运算符重载+ 2个不同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆