Okay, so I'm trying to override a function in a parent class, and getting some errors. here's a test case
#include <iostream>
using namespace std;
class A{
public:
int aba;
void printAba();
};
class B: public A{
public:
void printAba() new;
};
void A::printAba(){
cout << "aba1" << endl;
}
void B::printAba() new{
cout << "aba2" << endl;
}
int main(){
A a = B();
a.printAba();
return 0;
}
And here's开发者_StackOverflow中文版 the errors I'm getting:
Error 1 error C3662: 'B::printAba' : override specifier 'new' only allowed on member functions of managed classes c:\users\test\test\test.cpp 12 test
Error 2 error C2723: 'B::printAba' : 'new' storage-class specifier illegal on function definition c:\users\test\test\test.cpp 19 test
How the heck do I do this?
There's no need to put any keywords in the derived class to override a function.
class B: public A{
public:
void printAba();
};
But the base class's method should be virtual, to allow the method be selected depending on the actual identity of the variable.
class A{
public:
int aba;
virtual void printAba();
};
And if you create an B on stack and copy into A, slicing would occur. You should create a B on heap and cast the pointer as A.
A* a = new B();
a->printAba(); // if printAba is not virtual, A::printAba will be called.
delete a;
精彩评论