這是我的代碼:多態性與抽象類(C++)
#include <cstdlib>
#include <vector>
#include <iostream>
#include <cstring>
using namespace std;
//abstract class
class GMatrix {
string name;
int nrows;
int ncols;
public:
GMatrix(const string & n, int nr, int nc);
virtual GMatrix& add(const GMatrix&)= 0;
};
class RMatrix : public GMatrix {
vector<int>numbers;
public:
RMatrix(const string & n, int nr, int nc, vector<int> nums);
RMatrix& add(const RMatrix&);
};
GMatrix::GMatrix(const string& n, int nr, int nc){
name=n;
nrows=nr;
ncols=nc;
}
RMatrix::RMatrix(const string & n,int nr, int nc, vector<int> nums):GMatrix(n,nr,nc){
numbers=numbers;
}
RMatrix& RMatrix::add(const RMatrix& x){
for(int i =0; i = numbers.size(); i++){
numbers.at(i)+=x.numbers.at(i);
}
}
int main(int argc, char** argv) {
vector<int> n;
for (int i = 0; i < 16 ; i++){
n.push_back(i);
}
RMatrix a("a",4,4,n);
return 0;
}
正如你看到的,我的程序包括兩個類,一個(父類)的是在這裏抽象這樣的方法沒有的功能和一個孩子類。我的問題是,這個代碼無法建立。我嘗試創建一個對象作爲RMatrix對象,但編譯器顯示這樣的錯誤,我不明白:
main.cpp:48:13: error: cannot declare variable ‘a’ to be of abstract type ‘RMatrix’
main.cpp:18:7: note: because the following virtual functions are pure within ‘RMatrix’:
main.cpp:15:23: note: virtual GMatrix& GMatrix::add(const GMatrix&)
這不能解決問題,因爲常量GMatrix沒有成員數量 – 4pie0
@ privatedatapublicchannel2它不會立即導致工作代碼,但我相信它給提問者足夠的信息來修復他們的代碼並在將來避免該問題。 –
@Eric:除了代碼無法修復外,還有一個核心設計問題,因爲繼承關係不遵循LSP –