3

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

thanks

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 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.

4

3 回答 3

1

您不能重载返回类型。当调用函数或运算符时,编译器必须知道要调用哪一个。它不会根据分配给函数(运算符)调用的内容来推断。

看起来您正在寻求实现一些矩阵数学。也许如果您下载 DirectX SDK 或 OpenGL 并看看他们是如何做到的,您可能会得到一些关于如何正确做到这一点的想法。

于 2010-01-01T23:32:14.117 回答
1

函数的返回类型不是其签名的一部分,因此您不能在 block_matrix 中有两个 operator+(i,j) - 这将是一个模棱两可的调用。因此,在这一点上,多重继承有点像红鲱鱼。你就是不能那样做。

你真正想做什么,为什么?

无论如何,对于您的另一个问题:虚拟运算符在性能和操作方式方面与虚拟函数完全相同。你如何使用它们只是在语义上略有不同——但在幕后它们只是像其他任何函数一样。

于 2010-01-01T23:32:33.673 回答
0

我得到了它的工作,但它很不稳定。我很喜欢模板。

template<class T>
class Base1
{
};

template<class T>
class Base2
{
};

class Derived;
template<>
class Base1<Derived>
{
public:
     double foo(){return 0.1;}
};

template<>
class Base2<Derived>
{
public:
    int foo(){return 1;}
};

class Derived
    : public Base1<Derived>
    , public Base2<Derived>
{
public:
    using Base1<Derived>::foo;
};

int main()
{
     double sum = 0;
     Derived d;
     sum += d.foo(); //+ .1
     Base1<Derived> * pI = &d;
     sum += pI->foo(); //+ .1

     Base2<Derived> * pF = &d;
     sum += pF->foo(); //+ 1

     return (sum*10);
}

没有模板我无法让它工作,尽管它似乎应该能够。我不确定你是否可以以同样的方式只做模板化的成员函数,但我的直觉说“不”。

在代码组织方面,我会在 Derived 的定义或声明之后立即定义 Base# 的内容,因为这确实是它的用途。请记住,您可以使用typename Base1<Derived> something它使事情变得更漂亮。

编辑:哦,对了!它不允许您使用“使用”技巧或具有不同的返回类型,但它更简单:

class Derived
    : public Base1
    , public Base2
{
    double Base1::foo(){...}
    double Base2::foo(){...}
}

将这两种方法结合起来可能会有一种可怕的、可怕的、令人敬畏的方式,但我认为在使用代码时它实际上并没有帮助。我可能会回复你。

于 2010-01-02T04:34:04.337 回答