zoukankan      html  css  js  c++  java
  • 在继承类中,父类在子类中初始化问题,已解决

    #include<iostream>
    
    using namespace std;
    
    //继承与组合混搭情况下,构造和析构调用原则
    class Grandfather
    {
    public:
    	Grandfather( char * g)
    	{
    		this->G_t1=g;
    		cout<<"G_t1====== "<<G_t1;
    		cout<<"我是顶头的爷爷的构造函数
    ";
    	}
    
    	~Grandfather()
    	{
    		cout<<"我是顶头的爷爷的析构函数
    ";
    	}
    protected:
    	char *G_t1;
    private:
    };
    class Father:public Grandfather
    {
    public:
    	Father( char *f):Grandfather("hahahah")
    	{
    		F_t1=f;
    		cout<<"F_t1====== "<<F_t1;
    		cout<<"这是父亲的构造函数
    ";
    	}
    	~Father()
    	{
    		cout<<"这是父亲的析构函数 
    ";
    	}
    protected:
    	char *F_t1;
    private:
    };
    class Child:public Father
    {
    public:
    	Child():Father("dsa"),g1("sfsdfds"),g2("g2")//不懂
    	{
    
    		cout<<"这是孩子的构造函数 
    ";
    	}
    	~Child()
    	{
    		cout<<"这是孩子的析构函数 
    ";
    	}
    protected:
    	int C_t1;
    	Grandfather g1;//这里这两句有疑问,为什么Grandfather明明必须有形参,但是为什么这里初始化参数反而不对了呢?
    	Grandfather g2;
    private:
    };
    
    void objplay()
    {
    	Child c1;
    }
    int main()
    {
    	
    	objplay();
    	system("pause");
    	return 0;		
    }
    

      不明白的是这两句

     但是这好像是套路,必须这么做呢

    就像例如:

    #include<iostream>
    
    using namespace std;
    
    //继承与组合混搭情况下,构造和析构调用原则
    class Grandfather
    {
    public:
    	Grandfather( char * g)
    	{
    		this->G_t1=g;
    		cout<<"G_t1====== "<<G_t1;
    		cout<<"我是顶头的爷爷的构造函数
    ";
    	}
    
    	~Grandfather()
    	{
    		cout<<"我是顶头的爷爷的析构函数
    ";
    	}
    protected:
    	char *G_t1;
    private:
    };
    class Father:public Grandfather
    {
    public:
    	Father( char *f):Grandfather("hahahah")
    	{
    		F_t1=f;
    		cout<<"F_t1====== "<<F_t1;
    		cout<<"这是父亲的构造函数
    ";
    	}
    	~Father()
    	{
    		cout<<"这是父亲的析构函数 
    ";
    	}
    protected:
    	char *F_t1;
    private:
    };
    class Child:public Father
    {
    public:
    	Child():Father("dsa"),g1("sfsdfds"),g2("g2"),f1("f1")//不懂
    	{
    
    		cout<<"这是孩子的构造函数 
    ";
    	}
    	~Child()
    	{
    		cout<<"这是孩子的析构函数 
    ";
    	}
    protected:
    	int C_t1;
    	Father f1;
    	Grandfather g1;//这里这两句有疑问,为什么Grandfather明明必须有形参,但是为什么这里初始化参数反而不对了呢?
    	Grandfather g2;
    private:
    };
    
    void objplay()
    {
    	Child c1;
    }
    int main()
    {
    	
    	objplay();
    	system("pause");
    	return 0;		
    }
    

      运行结果是:

    发现一个真理没?只要调用一个Father就必须调用一个爷爷啊

    套路

  • 相关阅读:
    树的直径的两种求法
    2018CCPC吉林赛区(重现赛)部分题解
    2019中国大学生程序设计竞赛-女生专场(重现赛)部分题解C-Function(贪心+优先队列) H-clock(模拟)
    HDU-1693 Eat the Trees(插头DP)
    【巷子】---redux---【react】
    【巷子】---flux---【react】
    【JavaScript算法】---希尔排序
    【JavaScript算法】---快速排序法
    【JavaScript算法】---插入排序
    【深拷贝VS浅拷贝】------【巷子】
  • 原文地址:https://www.cnblogs.com/xiaochige/p/6613022.html
Copyright © 2011-2022 走看看