首页 > 编程语言 > 详细

C++ 继承_构造函数_析构函数

时间:2021-02-25 16:44:19      阅读:26      评论:0      收藏:0      [点我收藏+]

 

 

 

 

#include<iostream>
using namespace std;
class CExample
{
private:
    int a;
    int n;
public:
    //构造函数
    CExample(int b)
    {
        a=b;
        printf("constructor1 is called\n");
    }
    CExample(int c, int d)
    {
        a=c;
        printf("constructor2 is called\n");
    }
    CExample(int c, int d, int e)
    {
        a=c;
        printf("constructor2 is called\n");
    }
    //拷贝构造函数
    CExample(const CExample & c)
    {
        a=c.a;
        printf("copy constructor is called\n");
    }

    //析构函数
    ~CExample()
    {
        cout<<"destructor is called\n";
    }
    void show()
    {
        cout<<a<<endl;
    }
};
int main()
{
    CExample A(100);
    CExample B(12,24);
    A.show();
    B.show();
    return 0;
        //A.Show();
    //CExample B=A;
    //B.Show(); 
}

运行结果是:

constructor1 is called
constructor2 is called
100
12
destructor is called
destructor is called

 

 

attention:

 CExample A(100);
 CExample B(12,24)

 

//生成对象A  并用100初始化A。100就自动调用对象中的构造函数

//如果是CExample A(100,200) 那上面必须有一个构造函数的参数是两个,如果是的话,这一过程即CExample A(100);  CExample A(100,200) 

//执行结束后,析构函数会执行两次

//构造函数不能有相同的参数,会提示重载出错,n个构造函数执行,析构函数就会执行N次。

//可以有多个构造函数,但是只能有一个析构函数

 

C++ 继承_构造函数_析构函数

原文:https://www.cnblogs.com/kuangbendesaozhu/p/14447278.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!