0
点赞
收藏
分享

微信扫一扫

类和对象-----继承

Separes 2022-01-31 阅读 55

继承最大的作用就是节省重复的代码。在不同的类中却有相同的部分这时候就可以用到继承的语法来简化我们的代码。

继承的语法结构是

class 子类 : 继承方式 父类;

子类和父类也称。派生类和基类。

继承方式有3种

protected (将继承完的属性变成保护的属性)

private (将继承完的属性变成隐私属性)

public(保持其原本的属性继承)

class father{
    public:
        int money;
    private:
        int age;
    protected
        int weight;
};
class firstSon : public father{
    /*这里就相当于填了
    public:
        int money;
    private:
        int weight;
*/
};
class secondSon : protected father{       
     /*相当于填写了
    protected:
        int money;
        int weight;*/ 
};
class thirdSon : private father{
    /*相当于写了
    private:
        int money;
        int weight;*/
};

注意private属性的成员不能被子类访问!!!!(可以被继承但是不能访问可以用sizeof来验证)

当想子类的成员有有父类同名时候,优先访问子类自身的。可通过加作用域访问父类.

c++中可以多继承就是

class 子类:继承方式 父类,继承方式 父类....

但是2个父类有相同的属性要加上作用域辨别


多继承的会造成数据重复这时候我们可以采用虚继承的技术

class person{};
class father:virtual person{};
class mother:virtual person{};
class son:public father,public mother;

会继承后定义的类

--------------------------------

继承中父类先进行构造函数然后是子类构造析构最后是父类的析构

(上代码)

#include<iostream>
using namespace std;
class father {
	public:
		father() {
			cout<<"father µÄ¹¹Ô캯Êý"<<endl;
		}
		~father() {
			cout<<"father µÄÎö¹¹º¯Êý"<<endl;
		}
};
class son:public father {
	public:
		son() {
			cout<<"son µÄ¹¹Ô캯Êý"<<endl;
		}
		~son() {
			cout<<"son µÄÎö¹¹º¯Êý"<<endl;
		}
};
int main() {
	son a;
	return 0;
}


有说错的不准确的,望指出 

举报

相关推荐

0 条评论