如果我创建一个基类指针数组,在一个范围内创建一个派生类对象并将引用传递给该数组并在该范围内正确调用派生类的虚函数,但在该范围之外,我尝试调用虚函数,它忘记它是一个派生类。我尝试投射它,但它不起作用。
class Base{
public:
Base(string str) {name = str;}
virtual string toString() { return name;}
Base& operator=(const Base& b) {name = b.name; return *this;}
private:
string name;
};
class Derived: public Base{
public:
Derived(string str1, string str2) {name = str1; second = str2;}
virtual string toString() {return name + second;}
Derived& operator=(const Derived& d) {Base::operator=(d);
second = d.second; return *this;}
private:
string name;
string second;
};
int main(){
Base* baseArr[5];
int n;
cin >> n;
if(n==1){
Derived der("Derived", "Class");
baseArr[0] = &der;
baseArr[0]->toString() << endl; //this prints out "DerivedClass"
}
cout << baseArr[0]->toString(); //this prints out "Derived"
}
有没有办法在范围之外调用派生类的函数?