TestA Basic;
TestB *Advanced1 = &Basic; //Is this viable?
TestC *Advanced2 = &Basic; //And this?
没有,孩子不能指向父类型的对象。
TestB->AdvancedFunction1(); //Does this do what I think it does?
TestC->AdvancedFunction2(); //Or do implicit errors/problems occur?
它调用TESTB :: AdvancedFunction1(也就是说,如果你强迫(CAST)&基本以Advanced1)。结果可能是灾难性的。
TestB AdvVar1;
TestC AdvVar2;
AdvVar1 = Basic; //Does this do what is intended?
AdvVar2 = Basic; //Or do implicit errors occur?
根本不是。虽然有时候可能是合理的下调(将父亲投给孩子),但复制(除非operator =被定义)不起作用。
你应该做的,如果你想拥有所有指向父亲的孩子的名单,这里是你应该做的:
class TestA
{
public:
enum _type
{
IS_TESTA = 0,
IS_TESTB,
IS_TESTC
} type;
/* other variables */
TestA() {type = IS_TESTA;}
virtual void common_function() { /* do something with TestA data */ }
void father_function() {}
}
class TestB : public TestA
{
public:
/* variables */
TestB() {type = TestA::IS_TESTB;}
void common_function() { /* do something with TestA & TestB data */ }
void TestB_specific_function() {}
}
class TestC : public TestA
{
public:
/* variables */
TestC() {type = TestA::IS_TESTC;}
void common_function() { /* do something with TestA & TestC data */ }
void TestC_specific_function() {}
}
创建列表,你这样做:
TestA **list = new TestA *[size];
for (int i = 0; i < size; ++i)
if (for_any_reason_create_TestB)
list[i] = new TestB;
else if (for_any_reason_create_TestC)
list[i] = new TestC;
else
list[i] = new TestA;
现在,当你要使用的变量,当你想打电话给所有人共享的功能,即使每个子类有不同的方式实现它,你可以这样做:
for (int i = 0; i < size; ++i)
list[i]->common_function();
它会根据真实的物体类型自动调用TestA::common_function
,TestB::common_function
或TestC::common_function
。
如果要调用特定儿童的功能,你可以这样做(但不推荐):
for (int i = 0; i < size; ++i)
if (list[i]->type == TestA::IS_TESTB)
((TestB *)list[i])->TestB_specific_function();
else if (list[i]->type == TestA::IS_TESTC)
((TestC *)list[i])->TestC_specific_function();
这是我正在寻找的答案。有人突出了特定技术的特定漏洞。通过向TestA添加虚拟功能来测试它不会导致崩溃。 – SSight3
你试过打电话吗? –
是的。唯一的缺点(取决于视图)是它被称为base的函数而不是TestB的,但是将它设置为非虚拟解决。也就是说,即使TestA和TestB都具有虚拟性,我称之为。我会尝试混合虚拟和非虚拟。 – SSight3