//********************************
//** ch16_5.cpp **
//********************************
#include
class Base
{
public:
virtual Base* afn()
{
cout<<"This is Base Class. \n";
return this;
}
};
class SubClass:public Base
{
public:
SubClass* afn() //实为虚函数
{
cout<<"This is SubClass. \n";
return this;
}
};
void test(Base& x)
{
Base* b;
b = x.afn();
}
void main()
{
Base bc;
SubClass sc;
test(bc);
test(sc);
}
//*****************************************************************************
--------------------Configuration: ch16_5 - Win32 Debug--------------------
Compiling...
ch16_5.cpp
D:\EXERCISES\CH16_5\ch16_5.cpp(21) : error C2555: SubClass::afn : overriding virtual function differs from Base::afn only by return type or calling convention
D:\EXERCISES\CH16_5\ch16_5.cpp(8) : see declaration of Base
//*****************************************************************************
//恳请知其所以然者不吝赐教,大恩不言谢:)
SubClass* afn() //实为虚函数
{
cout<<"This is SubClass. \n";
return this;
}
====>
Base* afn() //实为虚函数
{
cout<<"This is SubClass. \n";
return (Base*)this;
}
//********************************
//** ch16_5.cpp **
//********************************
#include <iostream.h>
class Base
{
public:
virtual Base* afn()
{
cout<<"This is Base Class. \n";
return this;
}
};
class SubClass:public Base
{
public:
Base* afn() //实为虚函数
{
cout<<"This is SubClass. \n";
return (Base*)this;
}
};
void test(Base& x)
{
Base* b;
b = x.afn();
}
void main()
{
Base bc;
SubClass sc;
test(bc);
test(sc);
}
--------------------Configuration: TestVirtual - Win32 Debug--------------------
Compiling...
TestVirtual.cpp
Linking...
TestVirtual.exe - 0 error(s), 0 warning(s)
--------------------------------------------------------------------------------
This is Base Class.
This is SubClass.
Press any key to continue
用Dev-C++能通过,这个很正常,VC不支持这个标准。
VC6.0不支持根据函数的返回值来区分重载函数,用VC7.0可以通过。