尝试创建一个驱动程序类型类,其中,Base是在实例化时传递类型的驱动程序。在这种情况下,类型2用于构造正确的派生对象。
我的编译器在“类别基础”行上抛出了声明语法错误。
我的最终目标是能够做到这一点:
Base *B;
B = new Base(2);
if(B)
{
B->DoStuff();
B->DoMoreStuff();
delete B;
}
这是我的代码,无法编译......
class Base
{
public:
Base(int h);
virtual ~Base();
private:
int hType;
Base *hHandle;
};
class Derived1 : public Base
{
public:
Derived1();
virtual ~Derived1();
};
class Derived2 : public Base
{
public:
Derived2();
virtual ~Derived2();
};
Base::Base(int h)
{
hType = h;
switch(h)
{
case 1:
hHandle = new Derived1;
break;
case 2:
hHandle = new Derived2;
break;
}
}
Derived1::Derived1():Base(1)
{
printf("\nDerived1 Initialized\n\n");
}
Derived2::Derived2():Base(2)
{
printf("\nDerived2 Initialized\n\n");
}
下面是更新的代码以显示完整的来源。我想我现在明白为什么它不会编译。正如下面所指出的,我对“新”
的调用无限循环#include <stdio.h>
class Base
{
public:
Base();
Base(int h);
Create (int h);
virtual ~Base();
private:
int hType;
Base *hHandle;
};
class Derived1 : public Base
{
public:
Derived1();
virtual ~Derived1();
};
class Derived2 : public Base
{
public:
Derived2();
virtual ~Derived2();
};
Base::Base()
{
}
Base::Base(int h)
{
Create(h);
}
Base::Create(int h)
{
hType = h;
switch(h)
{
case 1:
hHandle = new Derived1;
break;
case 2:
hHandle = new Derived2;
break;
}
}
Derived1::Derived1()
{
printf("\nDerived1 Initialized\n\n");
}
Derived2::Derived2()
{
printf("\nDerived2 Initialized\n\n");
}
答案 0 :(得分:2)
看起来你正试图做class factory。
我建议您在Base中使用静态方法返回Derived1或Derived2。
class Base
{
public:
static Base* Create(int);
virtual void DoStuff() = 0;
}
class Derived1 : public Base
{
Derived1()
{
printf("\nDerived1 Initialized\n\n");
}
virtual void DoStuff()
{
}
}
class Derived2 : public Base
{
Derived2()
{
printf("\nDerived2 Initialized\n\n");
}
virtual void DoStuff()
{
}
}
Base* Base::Create(int n)
{
if (n==1)
return new Derived1();
else if (n==2)
return new Derived2();
else
return nullptr;
}
void main()
{
Base* B = Base::Create(2);
if(B)
{
B->DoStuff();
delete B;
}
}