私は、クロスプラットフォームクラスを書く方法を見つけようとしていますが、プラットフォーム固有のバージョンのクラスでは、仮想関数のコストやあらゆる種類の醜さを避けています。ここで私が試したことがあります。C++このクラス構造はどのように達成できますか?
PlatformIndependantClass.hpp
class PlatformIndependantClass {
public:
PlatformIndependantClass();
std::string GetPlatformName();
private:
PlatformIndependantClass* mImplementation;
};
LinuxClass.hpp
#include "PlatformIndependantClass.hpp"
class LinuxClass : public PlatformIndependantClass{
public:
std::string GetPlatformName();
};
WindowsClass.hpp
#include "PlatformIndependantClass.hpp"
class WindowsClass : public PlatformIndependantClass {
public:
std::string GetPlatformName();
};
PlatformIndependantClass.cpp
#include "PlatformIndependantClass.hpp"
#include "LinuxClass.hpp"
#include "WindowsClass.hpp"
PlatformIndependantClass::PlatformIndependantClass() {
#ifdef TARGET_LINUX
mImplementation = new LinuxClass();
#endif
#ifdef TARGET_WINDOWS
mImplementation = new WindowsClass();
#endif
}
std::string PlatformIndependantClass::GetPlatformName() {
return mImplementation->GetPlatformName();
}
LinuxClass.cpp
#include "LinuxClass.hpp"
std::string LinuxClass::GetPlatformName() {
return std::string("This was compiled on linux!");
}
WindowsClass.cpp
#include "WindowsClass.hpp"
std::string WindowsClass::GetPlatformName() {
return std::string("This was compiled on windows!");
}
main.cppに
#include <iostream>
#include "PlatformIndependantClass.hpp"
using namespace std;
int main()
{
PlatformIndependantClass* cl = new PlatformIndependantClass();
cout << "Hello world!" << endl;
cout << "Operating system name is: " << cl->GetPlatformName() << endl;
cout << "Bye!" << endl;
return 0;
}
これでコンパイルは正常ですが、セグメント化エラーが発生します。これは、プラットフォーム固有のクラスがPlatformIndependantClassを継承しているためです。構築時に、プラットフォーム固有のクラスのインスタンスが作成されるため、無限再帰が発生します。私が試してみるたびに、私はちょうど非常に混乱する!
どうすればこのようなデザインを適切に達成できますか?それともこれは単なる恐ろしい考えですか?私はクロスプラットフォームのクラスを書く方法を見つけようとしていましたが、クロスプラットフォームライブラリに関する結果が得られました。どんな助けも喜んで受け入れられます:)
「プラットフォームの無関係」とはどういう意味ですか? –
バーチャルファンクションはどれくらいの費用がかかりますか?ユーザーが気付くには十分ですか? – Mark
PS: "independent"には "a"がありません。 –