Redian新闻
>
请问c++为什么会编译失败?
avatar
请问c++为什么会编译失败?# Programming - 葵花宝典
j*e
1
源程序:
#include
class A
{
public:
virtual void h()const{ printf("A::h() const\n");}
virtual void h(){ printf("A::h() non-const\n");}
};
class C: public A
{
public:
virtual void h(){ printf("C::h() non-const\n");}
};
int main()
{
C obj;
C* p1 = &obj;
const C* p2 = p1;
A* p3 = (A*)p1;
const A* p4 = p3;
p1->h();
//p2->h(); ///// this line will cause compile fail!!! but why?
p3->h();
p4->h();
return 0;
}
输出结果:
C::h() non-const
C::h() non-const
A::h() const
问题:
avatar
t*t
2
add:
use A::h;
in class C

【在 j*******e 的大作中提到】
: 源程序:
: #include
: class A
: {
: public:
: virtual void h()const{ printf("A::h() const\n");}
: virtual void h(){ printf("A::h() non-const\n");}
: };
: class C: public A
: {

avatar
j*e
3
Is "use" a keyword in C++?
Please explain in more detail.

【在 t****t 的大作中提到】
: add:
: use A::h;
: in class C

avatar
j*e
4
you mean "using A::h"?
It works, but why is that necessary?

【在 t****t 的大作中提到】
: add:
: use A::h;
: in class C

avatar
t*t
5
yeah, i meant "using"
sorry, was writing perl these days, mixed up

【在 j*******e 的大作中提到】
: you mean "using A::h"?
: It works, but why is that necessary?

avatar
F*n
6
This is called "Name Hiding".
virtual void h()const is hided by void h() in class C.

【在 j*******e 的大作中提到】
: 源程序:
: #include
: class A
: {
: public:
: virtual void h()const{ printf("A::h() const\n");}
: virtual void h(){ printf("A::h() non-const\n");}
: };
: class C: public A
: {

avatar
d*d
7
in class C, you have redefined h(), therefore, all the h() in the base class
, no matter what the signatures are, are hiddin by the new h(). Then, a cons
t object can only call a const function......

【在 j*******e 的大作中提到】
: 源程序:
: #include
: class A
: {
: public:
: virtual void h()const{ printf("A::h() const\n");}
: virtual void h(){ printf("A::h() non-const\n");}
: };
: class C: public A
: {

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。