覆盖差分访问规范c ++ [英] overriding with difference access specification c++

查看:139
本文介绍了覆盖差分访问规范c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在进行iKM测试时遇到了一个问题。有一个基类有两个抽象方法与私有访问说明符。有一个派生类,它覆盖了这些抽象方法,但带有protected / public访问说明符。

I came across a question while taking iKM test. There was a base class with two abstract methods with private access specifier. There was a derived class which was overriding these abstract methods but with protected/public access specifier.

我从来没有遇到过这样的事情,其中​​重载的方法在派生类中有不同的访问规范。这是允许的吗?如果是,它是否符合基础和派生(即可安全替代)之间的IS A关系。

I never came across such thing where overridden methods in derived class had different access specification. Is this allowed ? If yes, does it comply to "IS A" relation between base and derived (i.e. safely substitutable).

你能指出我可以提供更多细节

Could you point me to some references which can provide more details on such usages of classes ?

谢谢。

推荐答案

的人指出这是合法的。

但是,IS-A部分不是那么简单。当涉及到动态多态性时,IS-A关系成立,即。所有你可以做的超级你也可以使用Derived实例。

However, "IS-A" part is not that simple. When it comes to "dynamic polymorphism" "IS-A" relation holds, I.e. everything you can do with Super you can also do with Derived instance.

但是,在C ++中,我们也有一些常被称为静态多态时间)。考虑下面的例子:

However, in C++ we also have something that is often referred as static polymorphism (templates, most of the time). Consider the following example:

class A {
public:
    virtual int m() {
        return 1;
    }
};

class B : public A {
private:
    virtual int m() {
        return 2;
    }
};

template<typename T>
int fun(T* obj) {
    return obj->m();
}



现在,当你尝试使用动态多态性 :

Now, when you try to use "dynamic polymorphism" everything seems to be ok:

A* a = new A();
B* b = new B();

// dynamic polymorphism
std::cout << a->m(); // ok
std::cout << dynamic_cast<A*>(b)->m(); // ok - B instance conforms A interface
// std::cout << b->m(); fails to compile due to overriden visibility - expected since technically does not violate IS-A relationship

...但是当你使用静态多态性时,你可以说IS-A关系不再成立:

... but when you use "static polymorphism" you can say that "IS-A" relation no longer holds:

A* a = new A();
B* b = new B();

// static polymorphism
std::cout << fun(a); // ok
//std::cout << fun(b); // fails to compile - B instance does not conform A interface at compile time

,改变方法的可见性是相当合法,但这是C ++中的一个丑陋的事情,可能会导致陷阱。

So, in the end, changing visibility for method is "rather legal" but that's one of the ugly things in C++ that may lead you to pitfall.

这篇关于覆盖差分访问规范c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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