我正在努力研究如何編寫跨平臺類,同時避免虛擬函數的成本和平臺特定版本的類中的任何類型的醜陋。這是我嘗試過的。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,它在構建時創建了特定於平臺的類的實例,因此我獲得了無限遞歸。每次嘗試時,我都會感到非常困惑!
我該如何正確實現這樣的設計?或者這只是一個可怕的想法。我一直在試圖找出如何編寫跨平臺類,但我只是得到了關於跨平臺庫的結果負載,任何幫助將被感激地接受:)
你是什麼意思的「平臺indenpendence」? –
虛擬功能的成本是多少 - 這對用戶來說是否足夠注意? – Mark
PS:「獨立」在其中沒有「a」。 –