首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++虚函数的一点有关问题

2012-12-15 
C++虚函数的一点问题#includeiostreamusing namespace stdclass A{public:void show(){coutThis is

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为什么要用别的方法
[其他解释]
引用:
C/C++ code?12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929……

感谢大神!!我那天在机房没有得到答案回来看才知道,谢谢你们,本人新手
[其他解释]
引用:
不可能的
但要做到输出很容易

C/C++ code?12345678910111213141516171819202122232425262728293031323334353637class A{public:    void show()    {        cout<<"This is A!"<<endl;    }};class B:public A{……

嗯,知道了,感谢!
[其他解释]
引用:
lz用的是什么编译器, 取地址和强制转换应该都是不起作用的
而且就算用强制转换,也应该是p = (B*)&amp;b,而不是p = (B*)p
虚函数的存在就是为了解决这个问题,lz为什么要用别的方法

我用的是VC++ 6.0

热点排行