inserting subclasses into a superclasses array in c++

发布于 2022-09-06 11:01:23 字数 1289 浏览 17 评论 0

This is one of those things where i just know im doing it wrong. My assignment is simple.

Create 3 classes in c++,

product ,software ,book. product is super, book and software are product. then make an array of pointers and fill the array with software and books.

so i've done the following

int main()
{
 Product *productList[10];          


 Book *pBook;                       
 Book q(5);
 pBook = &q;
 pBook->getPrice();

 Software *pSoftware;
 Software g(5);
 pSoftware = &g;
 pSoftware ->getPrice();


 productList[0] = pSoftware; // fill it with software, cannot do this.

Is there any way of inserting a subclass into a super classes array. Or should i define the array of pointers as something else.

class definitions below

class Product
{
public:

double price;

double getPrice();

Product::Product(double price){};
};


class Book: public Product
{
public:
Book::Book(double price)
    :Product(price)
{
}
double getPrice();
};

class Software: public Product
{
public:
Software::Software(double price)
    :Product(price)                 // equivalent of super in java?
{
}                                   // code of constructor goes here.
double getPrice();
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

昇り龍 2022-09-13 11:01:24

As the array is of type Product, you should declare pSoftware as a pointer to Product:

Product *pSoftware = new Software(5);
// ...
productList[0] = pSoftware;
小霸王臭丫头 2022-09-13 11:01:24

It's been a while, but what's the default inheritance type in C++? Should

class Book:Product
{

be

class Book: public Product
{

It's always a good idea to be explicit anyway.

记忆で 2022-09-13 11:01:24

Can't you just cast the software* to a product* to put it in your array?
productList[0] = (Product*)pSoftware;

—━☆沉默づ 2022-09-13 11:01:23

You should use public inheritance:

class Book : public Product {
...
};

[edit]

You should also declare getPrice() as virtual if you want to implement it differently in the child classes. This will make compiler call getPrice() of the right child class when you call getPrice() for a pointer to a Product:

virtual double getPrice();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文