c ++调用子类的重写函数而不是父类

时间:2016-02-23 01:06:52

标签: c++ inheritance override

我试图从我的子类中调用convert(double)方法:Kilogram。我将如何调用重写函数而不是原始函数。下面是我的三个班级的代码。

Main.cpp的

#include <iostream>
#include <string>
#include "Conversion.cpp"

using namespace std;

int userInput;


Conversion con;

void menu() {
    cout << "Select an option: " << endl;
    cout << "1) KG to Lbs " << endl;
    cout << "2) Celsius to Kelvin " << endl;
    cout << "3) Teaspoons to millilitres " << endl;
    cout << "4) Multiplication tables (x) " << endl;
    cout << "5) Powers Tables (x) " << endl;
    cout << "6) Exit " << endl;

    cin >> userInput;

    switch(userInput) {
        case 1:
            cout << con.convert(23.56);
            break;
        default:
            break;
    }
};

int main() {
    menu();
    system("pause");
    return 0;
}

Conversion.cpp

class Conversion {
public:
    Conversion::Conversion(void) {

    }

    virtual double Conversion::convert(double varrr){

        return varrr;
    }
};

Kilogram.cpp

#include "Conversion.cpp"

double pounds;

class Kilogram : public Conversion {
public:
    Kilogram::Kilogram() {

    }

    virtual double Kilogram::convert(double kilos) override {
        pounds = (kilos * 2.2);
        return pounds;
    }

};

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您的代码调用基本定义的原因是因为:

Conversion con;

...声明的类型和运行时类型都是基类型。要重新调用重写方法,运行时类型必须是给定的派生类型,并且声明的类型需要是派生类型,或者它需要是指向基类型的指针或引用。那就是:

Kilogram from_kilogram;
Conversion from_pounds;
Conversion* converter = &from_pounds;
if (is_kilograms) {
  converter = &from_kilogram;
}
result = converter->Convert(weight_in_pounds);