私は以下のエラーに関する非常に一般的な質問があります。私は受け取ったエラーを指摘するためにコーディングを簡略化しました。 (サブクラスメンバ関数内の親クラスのオブジェクトと変数にアクセスしようとするとエラーが出ます。コメントにエラーの概要を書きました)次のコードがあるとします。テンプレートによる継承(サブクラスメンバー関数内で親クラスの変数とオブジェクトにアクセス)
//here is the parent class
template<class T, int m, int n>
class A{
protected:
vector<vector<T>> elements;
int nrow;
int ncol;
public:
A();
}
A<T,m,n>::A():nrow(m),ncol(n){
for (int i = 0; i < nrow; i++){
vector<T> row(ncol, 0);
elements.push_back(row);
}//this is a constructor to assign MxN zero matrix
//here is the child class and member function assign() and pow()
template<class T, int n>
class B:public A<T,n,n>{
B();
B<T,n> assign();
}
template<class T, int n>
B<T, n>::B() : A<T, n, n>(){}//a constructor of child class for NxN square matrix
template<class T, int n>
B<T,n> B<T,n>::assign(){
A<T,n,2*n> a;
for (int i = 0; i < nrow; ++i){
for (int j = 0; j < ncol; ++j){
//this causes error saying that "Error 1 error C2248:'A<T,3,3>::elements' : cannot access protected member declared in class 'A<T,3,3>'"
a.elements[i][j] = elements[i][j];
}
}
b.elements[0][0] = a.elements[0][0];
return b;
}
私のコーディングが私の質問に答えるのに十分でない場合。私は完全な詳細を提供することができます。最終的な目標は、Nx2N matrix.aを作成し、NxNマトリックスの要素をmatrix.aの左半分に配置し、メンバー関数assign()内で計算を行うことです。 (またはそれも可能ですか?????)main.cppでは、私は3x3行列を呼び出しました。
コメントありがとうございます!だから問題を解決するために、私はクラス構造全体を再設計していますか?継承で私の目標を達成する方法はありますか? – SungwonAhn
"Redesign"は "継承を使用しない"という意味ではありません。スーパークラスとサブクラスに適切なアクセスレベルで追加のメソッドを定義して実装するだけで、実行することができるようになります。 –