小結:在搜索標準C++設計圖案的用於通過構造加載不同的文件C++設計模式:多種方式來加載文件
我有一個Base
類的一些功能,將被所有派生類可以使用(例如,Derived_A
,Derived_B
)。主要區別在於Derived_A
和Derived_B
覆蓋load
函數,該函數用於由構造函數加載數據文件(load
也可能在構造函數之外顯式調用)。
我跑進從這個意想不到的問題:load
功能由構造稱爲治療類爲Base
類型,但是當我使用一個默認的構造函數和顯式調用load
功能,則虛函數表允許預期load
函數被調用。 (我最近使用Python進行編程,我相信,由於打字很弱,總是會調用預期的功能)。這是一個經典的問題,但我無法找到一種方法來做到這一點。
以同樣的方式,我真的很喜歡Base::load
是純粹的虛擬/抽象(只有派生類將被實例化);然而,這不會編譯(我相信,因爲編譯器認爲純虛函數會被調用)。
你能幫忙嗎?
輸出:
加載瓦特/構造:
基地::負載FILE_A
基地::負載FILE_B加載瓦特/功能交結構:
Derived_A ::負載FILE_A
Derived_B :: load file_B
代碼:
#include <iostream>
#include <string>
class Base
{
public:
Base() {}
Base(std::string x)
{
load(x);
}
virtual void load(std::string x)
{
std::cout << "\tBase::load " << x << std::endl;
}
};
class Derived_A : public Base
{
public:
Derived_A() {}
Derived_A(std::string x): Base(x) {}
void virtual load(std::string x)
{
std::cout << "\tDerived_A::load " << x << std::endl;
}
};
class Derived_B : public Base
{
public:
Derived_B() {}
Derived_B(std::string x): Base(x) {}
void virtual load(std::string x)
{
std::cout << "\tDerived_B::load " << x << std::endl;
}
};
int main()
{
// simpler code, but it doesn't behave as I hoped
std::cout << "Loading w/ constructor:" << std::endl;
Base*der_a = new Derived_A(std::string("file_A"));
Base*der_b = new Derived_B(std::string("file_B"));
// this is what I want to do
std::cout << "Loading w/ function post construction:" << std::endl;
der_a = new Derived_A;
der_a->load(std::string("file_A"));
der_b = new Derived_B;
der_b->load(std::string("file_B"));
return 0;
}
我最終使用'loader'模式。非常感謝! – user 2012-03-26 19:44:06