C ++虚拟常量函数 [英] C++ Virtual Const Function

查看:138
本文介绍了C ++虚拟常量函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码段



  class Base 
{
public:
virtual void eval()const
{
std :: cout<<Base Const Eval\\\
;
}
};

class Derived:public Base
{
public:
void eval()
{
std :: cout<非const评估
}
};

int main()
{

派生d;
Base * pB =& d;

pB-> eval(); //这将调用基本eval()

return 0;为什么pB-> eval()会调用Base :: eval()函数,因为它是一个非常简单的方法。 )?



谢谢

解决方案

const和另一个不是。一个功能被另一个隐藏。 Derived中的函数隐藏了Base中的一个,因为它们具有相同的名称,但它们不是同一个函数。



我的编译器在这里给出警告,


Given the following snippet,

class Base
{
public:
    virtual void eval() const
    {
        std::cout<<"Base Const Eval\n";
    }
};

class Derived:public Base
{
public:
    void eval()
    {
        std::cout<<"Derived Non-Const Eval\n";
    }
};

int main()
{

    Derived d;
    Base* pB=&d;

    pB->eval(); //This will call the Base eval()

    return 0;
}

Why the pB->eval() will call the Base::eval()?

Thank you

解决方案

This is because one is declared const and the other isn't. One function is being hidden by the other. The function in Derived is hiding the one in Base because they have the same name while they aren't the same function.

My compiler gives a warning here, does yours?

这篇关于C ++虚拟常量函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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