C++虚函数的一点问题
#include<iostream>
using namespace std;
class A
{
public:
void show()
{
cout<<"This is A!"<<endl;
}
};
class B:public A
{
public:
void show()
{
cout<<"This is B!"<<endl;
}
};
class C:public A
{
public:
void show()
{
cout<<"This is C!";
}
};
void main()
{
C c;
B b;
A a,*p;
p=&a;
p->show();
//p=(B)p; 不成功
p=&b;
p->show();
p=&c;
p->show();
}
问题如下:
现在我想不用虚函数来解决二义性,我想让指针p强制类型转换,使得输出
This is A!
This is B!
This is C!
那么我该如何是好呢?该怎么做我上面的做法不成功。
[最优解释]
2楼正解,我来补充一下:
子类指针到基类指针的转换一般是自动的。当然也可以直接强制转换。
对于非虚函数而言
代码一,直接强制转换:
#include <iostream>
using namespace std;
class A
{
public:
void show(){cout<<"This is A!"<<endl;}
};
class B:public A
{
public:
void show(){cout<<"This is B!"<<endl;}
};
int main()
{
B b;
A a;
A *p=&a;
p->show();
((B*)p)->show();
return 0;
}
输出结果为:
This is A!
This is B!
代码二,自动转换:
#include <iostream>
using namespace std;
class A
{
public:
void show(){cout<<"This is A!"<<endl;}
};
class B:public A
{
public:
void show(){cout<<"This is B!"<<endl;}
};
int main()
{
B b;
A a;
A *p=&a;
p->show();
p=&b;
p->show();
return 0;
}
输出结果为:
This is A!
This is A!
对于虚函数而言
代码三,直接强制转换:
#include <iostream>
using namespace std;
class A
{
public:
virtual void show(){cout<<"This is A!"<<endl;}
};
class B:public A
{
public:
void show(){cout<<"This is B!"<<endl;}
};
int main()
{
B b;
A a;
A *p=&a;
p->show();
((B*)p)->show();
return 0;
}
输出结果为:
This is A!
This is A!
代码四,自动转换:
#include <iostream>
using namespace std;
class A
{
public:
virtual void show(){cout<<"This is A!"<<endl;}
};
class B:public A
{
public:
void show(){cout<<"This is B!"<<endl;}
};
int main()
{
B b;
A a;
A *p=&a;
p->show();
p=&b;
p->show();
return 0;
}
输出结果为:
This is A!
This is B!
[其他解释]
不可能的
但要做到输出很容易
class A
{
public:
void show()
{
cout<<"This is A!"<<endl;
}
};
class B:public A
{
public:
void show()
{
cout<<"This is B!"<<endl;
}
};
class C:public A
{
public:
void show()
{
cout<<"This is C!";
}
};
void main()
{
C c;
B b;
A a,*p;
p=&a;
p->show();
//p=(B)p; 不成功
//p=&b;
((B*)p)->show();
//p=&c;
((C*)p)->show();
}
[其他解释]
lz用的是什么编译器, 取地址和强制转换应该都是不起作用的
而且就算用强制转换,也应该是p = (B*)&b,而不是p = (B*)p
虚函数的存在就是为了解决这个问题,lz为什么要用别的方法
[其他解释]
感谢大神!!我那天在机房没有得到答案回来看才知道,谢谢你们,本人新手
[其他解释]
嗯,知道了,感谢!
[其他解释]
我用的是VC++ 6.0