2014-09-04 56 views
1

我有一個帶有幾個重載運算符的矩陣類,但是我需要擴展它。我有一些編譯錯誤。玩具程序,以顯示該問題:如何用繼承來管理運算符重載

template<typename T, int R, int C> 
class matrix { 
public: 
    matrix() {}; 
    matrix(const matrix<T,R,C>& rhs) {} 
    matrix<T,R,C> operator+(const matrix<T,R,C>& rhs) { 
       matrix<T,R,C> result(); /*some code*/ return result; 
    } 
    ~matrix() {} 
    matrix<T,R,C>& operator=(const matrix<T,R,C>& rhs) { 
     return *this; 
    } 
}; 

class point: public matrix<double, 1, 2> { 
public: 
    point(); 
}; 

int main() { 
    point p1; 
    point p2, p3; 
    p1 + p2 <---------error 

    p1 = p2 + p3; <-------error 
    return 0; 
} 

編譯器錯誤是:

In instantiation of ‘matrix<T, R, C> matrix<T, R, C>::operator+(const matrix<T, R, C>&) [with T = double; int R = 1; int C = 2]’: 
a.cpp:28:13: required from here 
a.cpp:7:93: error: could not convert ‘result<double, 1, 2>’ from ‘matrix<double, 1, 2> (*)()’ to ‘matrix<double, 1, 2>’ 

回答

2

傷腦筋再次解析。

matrix<T,R,C> result(); 

聲明瞭一個名爲result採取任何參數和返回matrix<T,R,C>功能。拿出包袱。


當我儘量延長我想從operator+()等子類的對象返回類。

然後你需要給派生類自己的操作符。基類函數應該如何知道它實際上在派生類上運行?