3.1为什么有对象的初始化
创建对象时,需要做某些初始化的工作,但是类的数据成员不能在声明类的时候初始化,所以编译器提供了一个构造函数来处理对象的初始化。
构造函数时一种特殊的成员函数,与其他成员函数不同,不需要自己调用,是在建立对象的时候自动执行
3.2 构造函数和析构函数
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
using namespace std;
class Test{
public:
//无参构造函数
Test()
{
a = 10;//完成对象的初始化
p = (char*)malloc(100);
strcpy(p,"aaaaaaaaaafffffffff");
cout<<"我是构造函数,被执行了"<<endl;
}
void print(){
cout<<p<<endl;
cout<<a<<endl;
}
~Test()
{
if(p!=NULL){
free(p);
}
cout<<"我是析构函数,被执行了"<<endl;
}
private:
int a;
char *p;
};
//给对象搭建一个舞台,研究对象的行为
void objplay()
{
//先创建的对象后释放
Test t1;
t1.print();
printf("分隔符\n");
Test t2;
t2.print();
}
int main()
{
objplay();
cout<<"hello...."<<endl;
system("pause");
return 0;
}
构造函数的种类
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
using namespace std;
class Test1{
public:
//无参构造函数
Test1()
{
this->a = 0;
this->b = 0;
cout<<"无参构造函数"<<endl;
}
Test1(int a,int b)
{
this->a = a;
this->b = b;
cout<<"有参构造函数"<<endl;
}
Test1(int a)
{
this->a = a;
this->b = 0;
cout<<"一个参数的有参构造函数"<<endl;
}
Test1(const Test1& obj)
{
cout<<"赋值构造函数"<<endl;
}
~Test1()
{
cout<<"我是析构函数,被执行了"<<endl;
}
public:
void print(){
cout<<this->a<<endl;
cout<<this->b<<endl;
cout<<"普通成员函数"<<endl;
}
private:
int a;
int b;
};
int main()
{
//括号法
Test1 t1(1,2);
t1.print();
//等号法,这里的等号,C++进行了功能性增强
Test1 t2 = (3,4);//出错是因为逗号表达式,相当于t2 = 4;所以这里要有一个,一个参数的构造函数
Test1 t3 = 5;
Test1 t4 = Test1(1,2);
t1 = t4; //把t4 copy 给 t1; 赋值操作
cout<<"hello...."<<endl;
system("pause");
return 0;
}