C ++多个继承自同名运算符 [英] C++ multiple inheritance off identically named operator
问题描述
是否可以从两个不同的抽象类继承名称相同的运算符,而该运算符的唯一区别是返回类型不同. 如果是这样,他们:
Is it possible to inherit identically named operator which only differ in return type, from two different abstract classes. If so, them:
-
实现运算符的语法是什么
what is the syntax for implementing operators
使用/解析运算符的语法是什么
what is the syntax for using/resolving operators
在一般情况下,与任何其他虚函数一样,开销是多少?
what is the overhead in general case, same as for any other virtual function?
如果您可以为我提供参考或示例代码
if you can provide me with a reference or sample code that would be helpful
谢谢
12struct abstract_matrix {
13 virtual double& operator()(int i, int j);
14};
15
16 struct abstract_block_matrix {
17 virtual double* operator()(int i, int j);
18 };
19
20struct block_matrix : abstract_matrix, abstract_block_matrix {
21
22};
块矩阵需要为两个运算符提供实现,因此取决于上下文,它可以是矩阵,也可以是块矩阵.我不知道如何提供特定于block_matrix类的实现. 现在,这是通过传递对象包装类型作为最后一个参数来完成的,但这似乎不是很干净.我想保留纯矩阵符号.
block matrix needs to provide implementations for both operators, so that it is either a matrix or a block matrix, depending on the context. I do not know how to provide implementation specific to block_matrix class. right now, it is done by passing object wrapped type as the last argument, but that does not seem very clean. I would like to retain pure matrix notation.
推荐答案
函数的返回类型不是其签名的一部分,因此,block_matrix中不能包含两个operator +(i,j)-这将是一个模棱两可的电话.因此,就这一点而言,多重继承在某种程度上是一个红鲱鱼.你就是做不到.
The return type of a function is not part of it's signature, so you can't have two operator+(i,j)'s in block_matrix - that would be an ambiguous call. So multiple inheritance is sort of a red herring here on this point. You just can't do that.
您真正想做什么,为什么?
What are you really trying to do, and why?
无论如何,对于您的另一个问题:虚拟运算符在性能和操作方式方面与虚拟函数完全相同.在使用方式上,语义上仅有细微的差异-但实际上,它们的功能与其他任何功能一样.
In any event, for your other question: virtual operators are exactly like virtual functions in terms of performance and the way they operate. There are just slight semantic differences in how you use them - but under the hood they're just functions like any other.
这篇关于C ++多个继承自同名运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!