純粋仮想ではないコンストラクターによって呼び出される純粋仮想関数を持つ抽象クラスを作成したいと考えています。以下は私のファイルですclass.hpp
:
#ifndef __CLASS_HPP__
#define __CLASS_HPP__
#include <iostream>
class Parent {
public:
Parent(){
helloWorld(); // forced to say hello when constructor called
};
virtual void helloWorld() = 0; // no standard hello...
};
class Child : public Parent {
public:
void helloWorld(){ // childs implementation of helloWorld
std::cout << "Hello, World!\n";
};
};
#endif
この例では、純粋仮想関数を持つ親クラスがありますhelloWorld()
。コンストラクターが呼び出されたときに、すべての派生クラスに「こんにちは」と言ってもらいたいです。helloWorld()
したがって、親クラスのコンストラクターにあるのはなぜですか。ただし、デフォルトのメソッドを使用するのではなく、すべての派生クラスを強制的に「こんにちは」と言う方法を選択する必要があります。これは可能ですか?これを g++ でコンパイルしようとすると、純粋仮想関数がコンストラクターによって呼び出されているというエラーが発生します。私main.cpp
は:
#include "class.hpp"
int main(){
Child c;
return 0;
}
を使用してコンパイルしg++ main.cpp -o main.out
ていますが、結果のエラーは次のとおりです。
In file included from main.cpp:1:0:
class.hpp: In constructor ‘Parent::Parent()’:
class.hpp:9:16: warning: pure virtual ‘virtual void Parent::helloWorld()’ called from constructor [enabled by default]
合法的な方法で同様の設定を取得する方法について何か提案はありますか?
新しい質問
DyP は、コンストラクターがオーバーライドされた関数を使用しないことに注意を向けたので、私ができるようにしたいことは、私がセットアップした方法では不可能です。ただし、派生コンストラクターに関数を呼び出すように強制したいのhelloWorld()
ですが、これを行う方法はありますか?