静的メンバー関数を持つクラスがあります (これは必要です)。クラスの非静的メンバーを使用できるようにするため。Static_This
クラスへのポインタであるa を定義しました。
template<class T>
class Energy_Minimizer
{
protected:
static Energy_Minimizer* Static_This;
Petsc_Vector<T>* Gradient;
Petsc_Vector<T>* Solution;
static int Form_Function_and_Gradient(Petsc_Vector<T> *Solution_,Petsc_Vector<T> *Gradient_, PetscReal *Function_Value_);
public:
Energy_Minimizer(MPI_Comm Communicator_);
void Add_Term(vector<int>& Indexes, void* Coefs, string Function_Name_);
virtual void Total_Energy()=0;
};
Static_This
クラスのコンストラクターに設定します。
template<>
Energy_Minimizer<double>::Energy_Minimizer(MPI_Comm Communicator_)
{
Communicator = Communicator_;
Static_This = this;
...
}
また、非静的仮想関数にアクセスできます:
int Energy_Minimizer<double>::Form_Function_and_Gradient(Petsc_Vector<double> *Solution_,Petsc_Vector<double> *Gradient_, PetscReal *Function_Value_)
{
Static_This->Solution = Solution_;
Static_This->Gradient = Gradient_;
// Call the user-defined routine to construct the function value, gradient
Static_This->Total_Energy();
return 0;
}
派生クラスに仮想関数 Total_Energy() を実装します。
class Strain_Solver : public Energy_Minimizer<double>;
void Strain_Solver::Total_Energy()
{
****** Here problem occurs ******
this->Add_Term(ij_Indexes, NULL , string("Alpha_Term"));
}
派生クラスの仮想関数から基底クラスの関数を呼び出します。私が抱えている唯一の問題は、派生クラスから基本クラスのメンバー関数を呼び出すとすぐに、データ (ここではソリューション) が破損することです。つまり、上記の例で Add_Term 関数を呼び出すと、基本クラスのソリューション ベクトルが突然破損します。割り当てが解除されるようなものです。