创建派生类对象的指针数组。 C ++。抽象基类

编程入门 行业动态 更新时间:2024-10-27 20:36:53
本文介绍了创建派生类对象的指针数组。 C ++。抽象基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要创建一个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 <100; ++ 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 ++。抽象基类

本文发布于:2023-08-04 13:24:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1296672.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   指针   抽象   对象   派生类

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!