你是否有遇過這樣的情況:
class Base {
public:
Base(int a) : A(a) {}
virtual ~Base(){}
// print function in Base class
void printA(){ std::cout << A << endl; }
private:
int A;
};
class Derived : public Base {
public:
Derived(int a, int b) : Base(a), B(b) {}
virtual ~Derived(){}
// print function in Derived class
void printB(){ std::cout << B << endl; }
private:
int B;
};
int main()
{
Base* b0;
int a=0, b=1;
b0 = new Derived(a,b);
b0->printA();
b0->printB();
return 0;
}
在執行到 b0->printB();的時候,compiler會出現以下錯誤:
這種時候就直接使用大招:
static_cast<Derived*>(b0)->printB();
就可以使用了。
!!!注意!!!
Base class pointer無法存取Derived class member是正常的。任意存取Derived class member其實是非常危險的,Base class pointer不應該知道自己new了什麼樣的derived class。除非你真的知道你在幹嘛,否則就請乖乖寫virtual function並用override(c++11)方式實作這些功能。
在 class Base裡面加上:
class Base {
public:
Base(int a) : A(a) {}
virtual ~Base(){}
// print function in Base class
void printA(){ std::cout << A << endl; }
virtual printB(){} // virtual function to be override
// virtual printB() = 0; // = 0: pure virtual function, must be override
private:
int A;
};
而在 class Derived 裡面加上override保險:
class Derived : public Base {
public:
Derived(int a, int b) : Base(a), B(b) {}
virtual ~Derived(){}
// print function in Derived class // override
void printB() override { std::cout << B << endl; }
private:
int B;
};
這樣就不會有compile error了。
https://stackoverflow.com/questions/2436125/c-access-derived-class-member-from-base-class-pointer