C++中的继承

2017-10-14  本文已影响0人  nethanhan

继承的概念

类之间的两大关系:组合和继承:

组合关系的代码示例:

class Memory
{
public:
    Memory()
    {
        cout << "Memory()" << endl;
    }
    ~Memory()
    {
        cout << "~Memory()" << endl;
    }
};

class Disk
{
public:
    Disk()
    {
        cout << "Disk()" << endl;
    }
    ~Disk()
    {
        cout << "~Disk()" << endl;
    }   
};

class Computer
{
    Memory mMem;
    Disk mDisk;
public:
    Computer()
    {
        cout << "Computer()" << endl;
    }
    ~Computer()
    {
        cout << "~Computer()" << endl;
    }
};
class Parent
{
    int mv;
public:
    void method() {};
};

class Child: public Parent  // 描述继承关系
{
};

继承关系代码示例:

#include <iostream>
#include <string>

using namespace std;

class Parent
{
    int mv;
public:
    Parent()
    {
        cout << "Parent()" << endl;
        mv = 100;
    }
    void method()
    {
        cout << "mv = " << mv << endl;
    }
};

class Child : public Parent
{
public:
    void hello()
    {
        cout << "I'm Child calss!" << endl;
    }
};

int main()
{   
    Child c;
    c.hello();
    c.method();
    
    return 0;
}

继承的访问级别

举一个例子:

class Parent
{
private:
    int mv;
public:
    Parent()
    {
        mv = 100;
    }
    
    int value()
    {
        return mv;
    }
};

class Child : public Parent
{
public:
    int addValue(int v)
    {
        //子类直接访问父类的私有成员变量
        mv = mv + v;    
    }
};

int main()
{   
    return 0;
}

运行结果如下:

nethanhandeMacBook-Pro-2:代码 nethanhan$ g++ 44-1.cpp 
44-1.cpp:27:9: error: 'mv' is a private member of 'Parent'
        mv = mv + v;    // 子类直接访问父类的私有成员变量
        ^
44-1.cpp:9:9: note: declared private here
    int mv;
        ^
44-1.cpp:27:14: error: 'mv' is a private member of 'Parent'
        mv = mv + v;    // 子类直接访问父类的私有成员变量
             ^
44-1.cpp:9:9: note: declared private here
    int mv;
        ^
2 errors generated.

结果里说到 mv 是一个私有成员变量,在子类中不能直接私有成员。所以需要使用另外一个关键字 protested

使用示例:

class Parent
{
//这里使用关键字 protected来声明
//子类就可以直接访问到
//而且外界不可以直接访问到
protected:
    int mv;
public:
    Parent()
    {
        mv = 100;
    }
    
    int value()
    {
        return mv;
    }
};

class Child : public Parent
{
public:
    int addValue(int v)
    {
        //子类可以直接使用父类的成员变量
        mv = mv + v;    
    }
};

继承方式

继承方式\父类成员访问级别 public protected private
public public protected private
protected protected protected private
private private private private

注意:

上一篇 下一篇

猜你喜欢

热点阅读