打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
构造函数全面解析
1
构造函数特点:
主要是在两方面起作用:
1,构造函数  在创建对象时 分配空间
2 构造函数   在创建对象时  初始化

析构函数:
在撤销函数时,收回占用的内存  以及其他的清理工作
--------------------------------------------------------------------------------
源代码1:
#include<iostream>
using namespace std;

class Point{
    private:
    int x,y;
    public:
    int Init(int x,int y){
        this->x=x;
        this->y=y;
    }
    int show(){
        cout<<x<<","<<y<<endl;
    }
};

int main(){
    Point p;
    p.Init(1,2);
    p.show();
}
结果:
 
 
编辑代码遇到的bug;
//类名没写全
//类名后面()
--------------------------------------------------------------------------------
2 
源代码2:
#include<iostream>
#include<cstring>
using namespace std;

class Person{
    private:
    char name[12];
    int age;
    char sex[4];
    
    public :
       Person(const char*n,int a,const char*s){//构造函数
        strcpy(name,n);
        age=a;
        strcpy(sex,s);
    }
    int Show(){
        cout<<"name:"<<name<<",age:"<<age<<",sex:"<<sex<<endl;
    }
    
};

int main(){
    Person p("zhao",12,"nan");
    p.Show();
}


3//构造函数主要是  无参构造函数  有参构造函数  拷贝构造函数
#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;

class Test{
    private:
    int a;
    char* p;
    
    public:
    Test();
    ~Test();
    void print(){
        cout<<a<<endl;
        cout<<p<<endl;
    }
};

Test::Test(){
    a=10;
    p=(char*)malloc(sizeof(100));
    strcpy(p,"Rita");
    cout<<"我是构造函数"<<endl;
}

Test::~Test(){
    if(p!=0){
        free(p);
    }
    cout<<"我是析构函数,我被调用调用了!"<<endl;
}

void objplay(){
    Test t1;
    Test t2;
    t1.print();
    cout<<endl<<endl;
    t2.print();
}

int main(){
    objplay();
    system("pause");
    return 0;
}



构造函数初始化列表:
 
 

1  Point::Point(int x1,int y1){x=x1;y=y1;}
2  Point::Point(int x1,int y2):x(x1),y(y1){}
3  Point::Point(int x1,int y1,const char*p1){x=x1;y=y1;strcpy(p,p1);}
4  Point::Point(int x1,int y1,const char*p1):x(x1),y(y1){
    strcpy(p,p1);
}

4 

分享知识,分享快乐!希望中国站在编程之巅!

               ----

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
c 中有些重载运算符为什么要返回引用
浅复制、深复制详解
最全的C\C 面试题解(2)
C++习题与解析(引用-03)
复制构造函数与赋值函数的区别
C++的一大误区
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服