#include<iostream>#include<string>
using namespace std;
class Test
{
private:int i;int j;
public:intgetI(){return i;}intgetJ(){return j;}Test(){
cout <<"Test() Begin"<< endl;
i =1;
j =2;
cout <<"Test() End"<< endl;;}};
Test gt;// Test() Begin 创建对象时调用构造函数// Test() Endintmain(){
cout <<"gt.i = "<< gt.getI()<< endl;// 1
cout <<"gt.j = "<< gt.getJ()<< endl;// 2
Test t1;// Test() Begin// Test() End
cout <<"t1.i = "<< t1.getI()<< endl;// 1
cout <<"t1.J = "<< t1.getJ()<< endl;// 2
Test* pt = new Test;// Test() Begin// Test() End
cout <<"pt->i = "<< pt->getI()<< endl;// 1
cout <<"pt->j = "<< pt->getJ()<< endl;// 2
delete pt;return0;}
带有参数的构造函数,满足重载规律
初始化和赋值是不一样的
初始化调用构造函数,赋值调用拷贝构造函数
#include<iostream>#include<string>
using namespace std;
class Test
{
public:Test(){
cout <<"Test()"<< endl;}Test(int v){
cout <<"Test(int v), v = "<< v << endl;}};intmain(){
Test t;// 调用 Test()
Test t1(1);// 调用 Test(int v) 第一种对象初始化方式
Test t2 =2;// 调用 Test(int v) 第二种对象初始化方式inti(100);// 初始化
cout <<"i = "<< i << endl;// 100return0;}
为了灵活的初始化对象数组,需要手动调用构造函数
#include<iostream>#include<string>
using namespace std;
class Test
{
private:int m_value;
public:Test(){
cout <<"Test()"<< endl;
m_value =0;}Test(int v){
cout <<"Test(int v), v = "<< v << endl;
m_value = v;}intgetValue(){return m_value;}};intmain(){
Test ta[3]={Test(),Test(1),Test(2)};// 对象数组初始化for(int i =0; i <3; i++){
cout <<"ta[i].getValue() = "<<ta[i].getValue()<< endl;}
Test t =Test(100);// 第三种对象初始化方式
cout <<"t.getValue() ="<< t.getValue();return0;}
2. 无参构造函数
当类中没有定义构造函数(包括拷贝构造函数)时,编译器默认生成一个无参构造函数,并且函数体为空
#include<iostream>#include<string>
using namespace std;
class Test
{
private:int i;int* p;
public:intgetI(){return i;}/*Test()
{
}
Test(const Test& t)
{
i = t.i;
}*/};intmain(){
Test t1;
Test t2 = t1;
cout <<" t1.i = "<< t1.getI()<< endl;
cout <<" t2.i = "<< t2.getI()<< endl;return0;}