pure virtual functions
In the C++ program:
#include<iostream.h>
class A
{
public: virtual void func()=0;
};
class B:public A
{
public: void show()
{
func();
}
};
void B::func()
{
cout<<"In B"<<endl;
}
int main()
{
B b;
b.show();
}
If the virtual function, func() is redefined within body of the class B, there is no error. But when usi开发者_Go百科ng the scope resolution operator, the compiler throws an error. Why is that?
This is not directly related to func
being virtual, you always need to declare it in the class:
class B:public A
{
public: void show()
{
func();
}
void func(); // add this
};
void B::func()
{
cout<<"In B"<<endl;
}
You have to declare that you redefine the member function func() in class B.
class B:public A
{
virtual void func();
public:
void show() {func(); }
};
精彩评论