请问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
问题:
为
#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
问题:
为