demo.cpp
#include<iostream>
#include"Banji.h"
using namespace std;
int main()
{
Banji b;
system("pause");
return 0;
}
Student.h
class Student
{
public:
Student();
~Student();
void setNum(int x);
int getNum();
private:
int m_iNum;
};
Banji.h
#include"Student.h"
class Banji
{
public:
Banji();
~Banji();
int setStu(int x);
int getStu();
private:
Student stu;
};
Student.cpp
#include"Student.h"
#include<iostream>
using namespace std;
Student::Student()
{
cout<<"Student"<<endl;
}
Student::~Student()
{
cout<<"~Student"<<endl;
}
void Student::setNum(int x)
{
m_iNum=x;
}
int Student::getNum()
{
return m_iNum;
}
Banji.cpp
#include"Banji.h"
#include<iostream>
using namespace std;
Banji::Banji()
{
cout<<"Banji()"<<endl;
}
Banji::~Banji()
{
cout<<"~Banji()"<<endl;
}
int Banji::setStu(int x)
{stu.setNum(x);}
int Banji::getStu()
{return stu.getNum();}
大家运行起来是没有问题的。
然后我现在改一下
如果我们的Student这个类的构造函数需要参数呢?
更改后的代码如下
demo.cpp
#include<iostream>
#include"Banji.h"
using namespace std;
int main()
{
Banji b(3);
system("pause");
return 0;
}
Student.h
class Student
{
public:
Student(int x);
~Student();
void setNum(int x);
int getNum();
private:
int m_iNum;
};
Banji.h
#include"Student.h"
class Banji
{
public:
Banji(int x);
~Banji();
int setStu(int x);
int getStu();
private:
Student stu;
};
Student.cpp
#include"Student.h"
#include<iostream>
using namespace std;
Student::Student(int x)
{
m_iNum=x;
cout<<"Student"<<endl;
}
Student::~Student()
{
cout<<"~Student"<<endl;
}
void Student::setNum(int x)
{
m_iNum=x;
}
int Student::getNum()
{
return m_iNum;
}
Banji.cpp
#include"Banji.h"
#include<iostream>
using namespace std;
Banji::Banji(int x)
{
Stu(x);
cout<<"Banji()"<<endl;
}
Banji::~Banji()
{
cout<<"~Banji()"<<endl;
}
int Banji::setStu(int x)
{
stu.setNum(x);
}
int Banji::getStu()
{
return stu.getNum();
}
你会发现,会报bug
为什么呢?
这是因为我们要知道,我们创建banji类的时候,
会先创建Stu,对象成员,然后再创建banji
然而我们如果在Banji的构造函数里面初始化Stu,那就来不及了!
这时候,我们应该使用初始化列表!
因为初始化列表在构造函数的函数体执行顺序之前!
能够在初始化Banji之前初始化Stu!
改法:
banji.cpp里面
Banji::Banji(int x):stu(x)
{
cout<<"Banji()"<<endl;
}