在定义属性或者函数中使用

#include <iostream>
using namespace std;

class Parent//父类
{
    private:
        int a;
        
    public:
        Parent(int _a):a(_a)
        {
            cout<<"Pareant的有参构造函数"<<endl;
            Parent_show();
        }
        Parent()
        {
            cout<<"Pareant的无参构造函数"<<endl;
            
        }
        void Parent_show()
        {
            cout<<"parent value  = "<<a<<endl;
        }
          virtual  void same_fun()
        {
            cout<<"same_fun() -parent  " ;
            Parent_show();
        }
};
class Son
{
    private:
        int a;
        
        
    public:
        Son(int _a,Parent _p):a(_a),p(_p)
        {
            cout<<"Son的有参构造函数"<<endl;
            Son_show();
        }
        Son()
        {
            cout<<"Son的无参构造函数"<<endl;
        }
        void Son_show()
        {
            cout<<"Son value  = "<<a<<endl;
        }
           void same_fun()
        {
            cout<<"same_fun() - son " ;
            Son_show();
        }
        Parent p;
};
    

int main()
{
    
    Parent p1(3);
    Son    s(4,p1);
    s.p.same_fun();
    

}
    

C++中类中使用 -类类型- 参数

 

------------------------------------------------------改为引用(指针更加可以)-----------------------------------------------------------------------------------------------

C++中类中使用 -类类型- 参数

C++中类中使用 -类类型- 参数

 

 

 

 

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>深度拷贝构造函数时候<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

---------------------------------------------------------------传类值,构造----------------------------------------------------------------------------------------------

C++中类中使用 -类类型- 参数

 

C++中类中使用 -类类型- 参数

 

结论:

传值构造不允许的,提示用引用来完成深度拷贝构造函数

 

-------------------------------------------------------------传引用,构造---------------------------------------------------------------------------------------------------

主函数和上面的一样

C++中类中使用 -类类型- 参数

---------------------------------------------------------传地址,构造------------------------------------------------------------------------------------------------------

C++中类中使用 -类类型- 参数

C++中类中使用 -类类型- 参数

结论,可以使用

相关文章: