防止覆盖和/或隐藏基类函数(C ++ 11) [英] Preventing overriding and/or hiding base class function (C++ 11)

查看:210
本文介绍了防止覆盖和/或隐藏基类函数(C ++ 11)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要防止甚至隐藏基类非虚拟函数一段时间,因为我学习了C ++,我不知道这是否符合道德,但C ++ 11功能给了我一个想法。假设我有以下:

I've wanted to prevent even the hiding of base class non-virtual function for a while since I learned C++, and I'm not sure if this would be ethical, but C++ 11 features gave me an idea. Suppose I have the following:

bases.h ....

bases.h....

#ifndef baseexample_h
#define baseexample_h

#include <iostream>

class Base{
    public:  
    void foo() {
        std::cout << "Base.foo()\n" << std::endl;
    }
};

class Derived: public Base{ 
    public:
    void foo(){
        std::cout << "Derived.foo()\n" << std::endl;
    }   
};

#endif

和main.cpp ...

and main.cpp...

#include "bases.h"
#include <iostream>

int main()
{

    Base base;
    Derived derived; 

    base.foo();
    derived.foo();

    std::cin.get();

    return 0;
};

当然输出是

Base.foo()

Derived.foo()

作为派生foo()函数隐藏基本foo函数。我想防止可能的隐藏,所以我的想法是改变头文件基本定义为:

as the derived foo() function hides the base foo function. I want to prevent possible hiding, So my idea was to change the header file Base definition to:

//.....
class Base{
    public:  
    virtual void foo() final {
        std::cout << "Base.foo()\n" << std::endl;
    }
};

class Derived: public Base{ 
    public:
    void foo(){ //compile error
        std::cout << "Derived.foo()\n" << std::endl;
    }   
};
//......

这似乎强制了我想要的编译器错误,防止覆盖和/或隐藏在c ++,但我的问题是,这是一个很好的做法,因为foo()从来不是一个虚拟函数开始?是否有缺点,因为我是一个滥用虚拟关键字?谢谢。

Which seems to enforce what I want with a compiler error, prevention of overriding AND/OR hiding in c++, but my question is, is this a good practice since foo() was never a virtual function to begin with? Is there a downside to this since i'm kind of abusing the virtual keyword? Thanks.

推荐答案

我会说,是的,这是坏的做法。当你不想要它时,你引入了多态性,只是为了防止名称隐藏。

I'd say that, yes, it's bad practice. You introduced polymorphism when you didn't want it, just to prevent name hiding.

但是名字隐藏有什么不好?显然,无论什么原因, Derived 的设计都希望在其基类中隐藏函数 foo 这是它的作用 - 也许它自己调用 Base :: foo 然后执行一些额外的活动,需要在派生

But what's so bad about name hiding? Obviously, for whatever reason, the design of Derived desires to hide the function foo in its base class; that is what it does — perhaps it makes its own call to Base::foo then performs some additional activity that is required within Derived.

试图颠覆这是不够的;

如果您 >真正需要来调用基本函数,使用 derived.Base :: foo(),但是要注意你基本上打破了类 Derived ,您应该使用文档。

If you really need to call the base function, use derived.Base::foo(), but be aware that you are essentially breaking the API of the class Derived, which you should instead use as documented.

这篇关于防止覆盖和/或隐藏基类函数(C ++ 11)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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