【问题标题】:Use one class method that implements other class methods as well as its own使用一个实现其他类方法以及它自己的类方法
【发布时间】:2011-07-13 12:40:03
【问题描述】:

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

Hatchback -> Car -> Vehicle;

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

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

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

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

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

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

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

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

object.print();

它通过车辆打印方法,然后是汽车打印方法,然后是掀背车打印方法。

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

不仅如此,我还有很多其他类别,包括汽车、公共汽车和卡车,它们都继承自车辆,以及集装箱、油轮、平板车、摩托车、运输 ETC ETC,它们都继承自汽车、卡车和公共汽车。

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

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

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

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

【问题讨论】:

    标签: c++ class polymorphism multiple-inheritance


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        在 Car::print() 中打印出汽车属性,然后调用 Vehicle::print()。 在 Hatchback::print() 中打印出掀背车属性,然后调用 Car::print() 以此类推

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-11-15
          • 1970-01-01
          • 2017-02-27
          • 1970-01-01
          • 2015-11-11
          • 2014-01-22
          • 1970-01-01
          • 2014-01-30
          相关资源
          最近更新 更多