C++改变基类成员在派生类中的访问属性
生活随笔
收集整理的這篇文章主要介紹了
C++改变基类成员在派生类中的访问属性
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用using聲明可以改變基類成員在派生類中的訪問屬性。我們知道基類的公有成員經過公有繼承,在派生類中其屬性為public的,但是通過using 聲明,我們可以將其改為private或protected屬性。
enum language{cpp, java, python,javascript, php, ruby};class book { public:void setprice(double a);double getprice()const;void settitle(char* a);char * gettitle()const;void display(); private:double price;char * title; };class codingbook: public book { public :void setlang(language lang);language getlang(){return lang;} private:language lang;using book::setprice; }; int main() {codingbook think;think.setlang(cpp);think.settitle("Thinking in C++");think.setprice(78.9); //compile errorreturn 0; }通過例1這樣的定義,則下面的主函數就會編譯錯誤,在think類對象調用setlang和settitle函數時都不會有問題,因為這兩個函數的屬性為public,可以訪問。唯獨setprice函數通過using聲明后,由public屬性變為了private屬性了。
總結
以上是生活随笔為你收集整理的C++改变基类成员在派生类中的访问属性的全部內容,希望文章能夠幫你解決所遇到的問題。