问题描述
我需要创建一个100个指向一个抽象类派生的两个类的对象的数组。
数组的第一个元素是 B类
,第二个是 C
,第三个是 B
等。 >
A
同时是基础和抽象类。
例如:
class A
{
public:
A
virtual double pureVirtualMethod()= 0;
};
B类:public A
{
};
class C:public A
{
};
在 main()
一个指向任何派生类的指针数组。
我不能使用Stl或Boost。
评论是正确的。你可以在5秒内google答案。
在任何情况下...
您需要定义A的构造函数的主体,或删除声明并使用默认的
直到你删除数组,以避免内存泄漏:)
A
{
public:
A(){} //< ----- ADDED BODY
virtual double pureVirtualMethod()= 0;
};
int main()
{
A * names [100];
for(int i = 0; i if(i%2)
names [i] = new C
else
names [i] = new B();
}
I need to make an array of 100 pointers to objects of two classes that are derived from an abstract class.
First element of array is of class B
, second is C
, third is B
etc.
A
is base and abstract class at the same time.
For example:
class A
{
public:
A();
virtual double pureVirtualMethod() = 0;
};
class B: public A
{
};
class C: public A
{
};
In main()
I need to make an array of pointers that will point to any of the derived classes.
I can't use Stl or Boost.
The comments are right. You can google the answer in 5 seconds.In any case...
You need to define the body of the constructor for A, or remove the declaration and use the default one
Up to you to delete the array to avoid a memory leak :)
class A
{
public:
A() {} // <----- ADDED BODY
virtual double pureVirtualMethod() = 0;
};
int main()
{
A* names[100];
for (int i = 0; i < 100; ++i)
if (i % 2)
names[i] = new C();
else
names[i] = new B();
}
这篇关于创建派生类对象的指针数组。 C ++。抽象基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!