摘要:寻找通过构造函数加载不同文件的标准C++设计模式
我有一个Base
类,其中包含所有派生类(例如Derived_A
,Derived_B
)将使用的一些功能。主要区别在于Derived_A
和Derived_B
覆盖了load
函数,该函数由构造函数用于加载数据文件(load
也可以在构造函数外显式调用)。
我遇到了一个意想不到的问题:构造函数调用的load
函数将类视为Base
类型,但是当我使用默认构造函数并显式调用load
函数时,虚拟函数表允许调用预期的load
函数。
这似乎是一个经典问题,但我找不到解决方法(我最近正在使用Python进行编程,因为弱类型,所以我认为它总是会调用预期的函数)。
同样地,我真的希望Base::load
是纯虚/抽象的(只有派生类将被实例化);但是,这样无法编译(我相信这是因为编译器看到将调用纯虚函数)。
你能帮忙吗?
输出:
使用构造函数加载:
Base::load file_A
Base::load file_B 使用后构造函数加载:
Derived_A::load 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;
}