class AT { public: int f1(){return 1;} int ax; };class BT:public AT {};int ft(AT *& at) { return at->ax; }void CMfc1Dlg::OnButton1() { // TODO: Add your control notification handler code here
BT* po = new BT; po->ax = 6; int r = ft(po); CString str; str.Format("%d",r); AfxMessageBox(str);
如果需要转换,用dynamic_cast
{
public:
int f1(){return 1;}
int ax;
};class BT:public AT
{};int ft(AT *& at)
{
return at->ax;
}void CMfc1Dlg::OnButton1()
{
// TODO: Add your control notification handler code here
BT* po = new BT;
po->ax = 6;
int r = ft(po);
CString str;
str.Format("%d",r);
AfxMessageBox(str);
}这样是不行的,ft((AT*)po)也不行,非要ft((AT*&)po)才行.习惯了对传引用的参数直接赋值了,这里没通过编译表示不解
例如比较常见的问题
void fun(int*& p)
{
p = new int[10];
//...
for(int i=0; i != 10; ++i)
{
p[i] = i + 1;
}
}// 调用
int* p = NULL;
fun(p);
printf("%d", p[3]);
你如果直接传递一个指针进函数
c++必须明确的知道这个指针所指向的数据类型
这样才好调用该指针所对应的类对象的虚函数假设有这样一种情况
CDerived : public CBase;
CDerived d;
CBase *p = &d;
函数声明void Fun(ClassA *& ca);
调用:Fun(p);
这时编译器就不知道你的p所指向的对象到底是CDerived还是CBase了
因为基类指针可以指向派生类对象,也就产生了一对多的关系,指针出现了多义性
这时你在函数调用的时候就要强制设定参数类型,来消除这个多义性