c++

208 阅读1分钟
class stu
{
    private:
    // 私有数据只能由成员函数调用
    int age;
    const string name; //const 成员变量只能用构造函数初始化
    static int _set;
    public:
    //函数声明
    void setage(int n);
    stu(int a,string b);
    static void set();//static成员函数,没有this指针,只能访问static变量
     void _show() const; //const成员函数,不能修改任何成员变量 
};
//函数定义
void stu::setage(int n)
{
    age = n; //编译过程种加入this指针
}
void stu::set()
{
    _set = 3;
}
stu::stu(int a,string b):age(a),name(b)
{
}
void stu::_show() const{
    cout << age;
}
  • 继承
 //继承和派生
class father
{
    public:
     int money = 1;
     father(int _p)
     {
         _private = _p;
     }
     void show();
    private:
     int _private ;
};
// 继承的三种方式
class son_1:public father 
{
    //修改继承后的权限
    public:
    using father::_private; // error,不可见
    int _sage;
    private:
     using father::money ;
    //使用父类的构造函数


    //子类与父类函数重名
    public:
    void show();
    /*
    son_1 s;          // 实例化
    s.show();         // 调用子类
    s.father::show()  // 调用父类
    */     
};

继承之间的作用关系

image.png

 C _cobj;//建立C类的一个实例
 cout << _cobj.n << endl //首先在C类作用域中寻找变量n
      << _cobj.func()<< endl; //在C类作用域中找不到func()
                                在B类作用域找不到func()
                                在A类作用域找到func()

继承之间的内存关系