C++构造函数和析构函数初步认识

构造函数
1.构造函数与类名相同,是特殊的公有成员函数。
2.构造函数无函数返回类型说明,实际上构造函数是有返回值的,其返回值类型即为构造函数所构建到的对象。
3.当新对象被建立时,构造函数便被自动调用,实例化的每个对象仅调用一次构造函数。
4.构造函数可以被重载(即允许有多个构造函数),重载由不同参数表进行区分,构造时系统按照函数重载规则选择一个进行执行。
5.如果类中没有构造函数,则系统会给出一个缺省的构造函数: 类名(){}
6.只要我们定义了构造函数,则系统便不会生成缺省的构造函数。
7.构造函数也可在类外进行定义。
8.若构造函数是无参的或者各个参数均有缺省值,C++编译器均认为是缺省的构造函数。但是注意,缺省的构造函数只允许有一个。
 
 
析构函数
1.析构函数无返回值无参数,其名字与类名相同,只在类名前加上~, 即: ~类名(){.......}
2.析构函数有且只有一个
3.对象注销时自动调用析构函数,先构造的对象后析构
//Test1.h
#include<iostream> using namespace std; class Test { private: long b; char a; double c; public: Test(); //Test(char a = 0);      //无参数的和各个参数均有缺省值的构造函数均被认为是缺省构造函数,缺省构造函数只能存在一个 Test(char a); Test(long b, double c);          //参数列表不同的构造函数的重载 ~Test() //析构函数有且只能有一个,析构顺序为先构造的后析构 { cout<<"The Test was free."<<this<<endl; } void print(); }; Test::Test() { cout<<"The Test was built."<<this<<endl; this->a = 0; this->b = 0; this->c = 0; } Test::Test(char a) { cout<<"The Test was built."<<this<<endl; this->a = a; } Test::Test(long b, double c) { cout<<"The Test was built."<<this<<endl; this->a = '0'; this->b = b; this->c = c; } void Test::print() { cout<<"a = "<<this->a<<" b = "<<this->b<<" c = "<<this->c<<endl; }

  

//Test.cpp
#include<iostream> #include"Test1.h" using namespace std; void main() { Test bt; bt.print(); Test bt1('a'); bt1.print(); Test bt2(3,7); bt2.print(); }

  运行结果

posted @ 2019-01-25 11:18  C_hp  阅读(3760)  评论(0编辑  收藏  举报