派生方法不在基类中调用 [英] Derived method in not called in base class

查看:144
本文介绍了派生方法不在基类中调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何放一个正确的标题。抱歉我的问题对我很难。

I don't know how to put a right title. sorry by my problem is very hard with me.

我有一个类myCal.h:

I have a class myCal.h:

class myCal
{
public:
    myCal();
    int add(int a, int b);
    int sub(int a, int b);
    int expresstion(int a, int b, int c);
};

和myCal.cpp:

and myCal.cpp:

myCal::myCal()
{
}

int myCal::add(int a, int b)
{
    return a+b;
}

int myCal::sub(int a, int b)
{
    return a-b;
}

int myCal::expresstion(int a, int b, int c)
{
    return add(sub(a, b), c);
}

在main.cpp中,我有类mockcal像这样:

in main.cpp, i have class mockcal like this:

class mockcal : public myCal
{
public:
    int sub(int a, int b)
    {
        return 100;
    }
    int expresstion(int a, int b, int c)
    {
       return myCal::expresstion(a,b,c);
    }
};

如果我运行myCal.expresstion(3,2,1),返回值为2, OK,
,但是当我运行mockCal.expresstion(3,2,1),返回值仍然是2,我想它返回101。

if I run myCal.expresstion(3,2,1), the return value is 2, that's OK, but when I run mockCal.expresstion(3,2,1), the return values still is 2, I want it return 101.

帮助我做这个,但不要改变任何在mockCal :: expresstion。
非常感谢。

please help me to do this, but do not change anything in mockCal::expresstion. Thanks so much.

推荐答案

你需要使方法 int sub ,int b) virtual在你的代码中的基类中( myCal 类),如果你想覆盖 mockcal class

You need to make the method int sub(int a, int b) virtual in the base class ( myCal class in your code), if you want to override it in the mockcal class

class myCal
{
   public:
   //...
   virtual int sub(int a, int b);
   //..
};

这篇关于派生方法不在基类中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆