j*******e 发帖数: 674 | 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
问题:
为 |
t****t 发帖数: 6806 | 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 : {
|
j*******e 发帖数: 674 | 3 Is "use" a keyword in C++?
Please explain in more detail.
【在 t****t 的大作中提到】 : add: : use A::h; : in class C
|
j*******e 发帖数: 674 | 4 you mean "using A::h"?
It works, but why is that necessary?
【在 t****t 的大作中提到】 : add: : use A::h; : in class C
|
t****t 发帖数: 6806 | 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?
|
F*****n 发帖数: 1552 | 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 : {
|
d*******d 发帖数: 2050 | 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 : {
|