使用一个实现其他类方法的类方法以及它自己的方法

时间:2011-03-11 13:57:31

标签: c++ class polymorphism multiple-inheritance

我正在用C ++编程,我有3个相互继承的类:

Hatchback -> Car -> Vehicle;

我想使用void print()方法打印每个类的属性

每个类都有一个Print方法,可以打印自己的属性。

void Vehicle::print()
{
   // Vehicle attributes
}

void Car::print()
{
   // Car attributes
}

void Hatchback::print()
{
   // Hatchback Attributes
}

我创建了一个对象,它在一个构造函数中初始化ALL类中的所有属性:

Hatchback hatchback("L880UCD", "Vauhall", "Corsa", 
                    "White", "None", "Car", "Hatchback", 
                    3, 5, "Manual", 3, 2, 1);

问题是,我想使用一种打印方法打印所有属性,所以当我打电话时,

object.print();

它通过车辆打印方法,然后是Car打印方法,然后是Hatchback Print方法。

我知道我可以打印Hatchback打印方法中的所有属性,因为每一件事都是继承的。如果可能的话,我想避免在一个类方法中打印所有3个类的数据...我希望每个类都处理它的OWN方法和函数!

不仅如此,我还有很多其他课程,包括汽车,公共汽车和货车,包括汽车,集装箱,油轮,平板车,摩托车,过境ETC等所有汽车,货车和公共汽车的内容。

所以我不想在每个底层派生类中编写Print Vehicle!

如果有办法做到这一点,我会非常感谢你的回应。

我尝试过使用虚函数,但得出的结论是,他们只是选择在运行时使用哪种方法,而不是合并打印函数。

感谢阅读!对不起,如果它是一个模糊或Noob问题...我是Stack Overflow的新手! :)

3 个答案:

答案 0 :(得分:7)

如果您询问是否可以从派生类调用基类方法,那么是的,您可以:

void Vehicle::print() {
   std::cout << "Vehicle attributes" << std::endl;
}

void Car::print() {
   Vehicle::print();
   std::cout << "Car attributes" << std::endl;
}

答案 1 :(得分:3)

让Hatchback :: print()调用Car :: print(),然后可以调用Vehicle :: Print()

答案 2 :(得分:2)

在Car :: print()中打印出汽车属性,然后调用Vehicle :: print()。 在Hatchback :: print()中打印出两厢属性,然后调用Car :: print() 等等