关于C++虚拟函数的问题

来源:百度知道 编辑:UC知道 时间:2024/06/18 12:46:07
#include "iostream.h"

class Base
{
public:
virtual Base* afn()
{
cout<<"This is Base class.\n";
return this;
}
};

class SubClass:public Base
{
public:
virtual SubClass* afn() //实为虚拟函数
{
cout<<"This is SubClass. \n";//问题overriding virtual function differs from 'Base::afn' only by return type or calling convention
return this;
}
};

void test (Base& x)
{
Base* b;
b=x.afn();
}

void main()
{
Base bc;
SubClass sc;
test(bc);
test(sc);
}
我是按照书上写的 不知道为什么会有错误 请高手指点!
这个不是函数重载的问题,而是虚函数的另一个种写法。

virtual SubClass* afn()

这个你要是把afn函数里面+个参数还可以实现一下函数的的重载

如果是你这样不能实现函数的重载,因为重载函数不以返回值来区分.

把virtual SubClass* afn() 改为:

virtual Base * afn()或者Base * afn()都可以

建议你去看一下虚函数的作用;

下面是我跟你改的个简单一点的虚函数的作用:

#include "iostream.h"

class Base
{
public:
virtual void afn()
{
cout<<"This is Base class.\n";

}
};

class SubClass:public Base
{
public:
virtual void afn()
{
cout<<"This is SubClass. \n";

}

};

void test (Base& x)
{
x.afn();
}

void main()
{
Base bc;

SubClass sc;

test(bc);

test(sc);

}

这个代码 你是在什么编译器里用的? 不同的编译器会有不同的编译结果,我在Dev-C++里编译通过了,有些书上的是标准C++在vc下是通不过的

1.overriding virtual function differs from 'Base::afn' only by return type or calling convention