构造函数特点:
主要是在两方面起作用:
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:
#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);
}