C++改变基类成员在派生类中的访问属性

使用 using 声明可以改变基类成员在派生类中的访问属性。我们知道基类的公有成员经过公有继承,在派生类中其属性为 public 的,但是通过 using 声明,我们可以将其改为 private 或 protected 属性。

【例 1】
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;
};

通过例 1 这样的定义,则下面的主函数就会编译错误,在 think 类对象调用 setlang() 和 settitle() 函数时都不会有问题,因为这两个函数的属性为 public,可以访问。唯独 setprice() 函数通过 using 声明后,由 public 属性变为了 private 属性了。
int main()
{
    codingbook think;
    think.setlang(cpp);
    think.settitle("Thinking in C++");
    think.setprice(78.9);  //compile error
    return 0;
}