问题描述
你好,
我有以下代码:
class Base {
public:
virtual void f(){cout<< "碱:: f()的" << endl;}
virtual void f(int){cout<< "碱:: F(INT)" << endl;}
};
class派生:public Base {
void f(){cout<< "衍生:: f()的" << endl;}
};
int main(){
Base * ptr = new Derived();
ptr-> f();
ptr-> f(1);
返回0;
}
如您所见,我将Base :: f()从公共覆盖到私有访问
权限。作为我的Java人,我期待编译器错误。
但令我惊讶的是,该程序运行良好,并调用私有
版本?这是一个编译器错误(我使用g ++),还是将函数
显式转换为public?谢谢。
Hello there,
I have the following code:
class Base {
public:
virtual void f() {cout << "Base::f()" << endl;}
virtual void f(int) {cout << "Base::f(int)" << endl;}
};
class Derived : public Base {
void f() {cout << "Derived::f()" << endl;}
};
int main() {
Base *ptr = new Derived();
ptr->f();
ptr->f(1);
return 0;
}
As you can see, I overridden Base::f() from public, to private access
permission. Being the Java guy that I am, I expected a compiler error.
But to my surprise, the program ran fine, and called the private
version? Is this a compiler bug (I use g++), or is the function
explicitly converted to public? Thank you.
推荐答案
这在C ++中是允许的。但是,你不能提供比超类提供的更多的b $ b可访问性,换句话说,它是一个
私有成员,子类中的公共禁止当前
标准。
That''s allowed in C++. However, you''re not allowed to provide more
accessibility than provided by super class, in other words making it a
private member a public in subclass is prohibited under the current
standard.
Java造成许多误解。
Java creates many misapprehensions.
两者都没有。 Base :: f是公共的,Derived :: f是私有的,就像你一样
表示它们应该是。静态检查访问。也就是说,ptr->; f()
可以调用f,因为f在Base中是公共的。尝试使用指针
派生。
-
Pete
Roundhouse Consulting,有限公司()作者The
标准C ++库扩展:教程和参考
()
Neither. Base::f is public, and Derived::f is private, just like you
said they should be. Access is checked statically. That is, ptr->f()
can call f because f is public in Base. Try it with a pointer to
Derived.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)
这是C ++中允许的。但是,你不能提供比超类提供的更多的b $ b可访问性,换句话说,它是一个
私有成员,子类中的公共禁止目前
标准。
That''s allowed in C++. However, you''re not allowed to provide more
accessibility than provided by super class, in other words making it a
private member a public in subclass is prohibited under the current
standard.
不,它不是。我认为你对使用
指令的规则感到困惑,这些指令不允许增加访问权限。
-
Pete
Roundhouse Consulting,Ltd。()作者
标准C ++库扩展:教程和参考
()
No, it''s not. I think you''re confusing this with the rule about using
directives, which are not allowed to increase access.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)
这篇关于覆盖具有较低权限的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!