第一课——内联成员函数
其有两种定义方式:
- inline + 成员函数
- 整个函数体出现在类定义内部
class B
{
inline void func1(); //func1是内联成员函数
void func2() //func2是内联成员函数
{
};
};
void B::func1(){}
第一课——构造函数
- 当类中自定义了构造函数后,编译器不再自动生成无参数的默认构造函数
class Complex{
private:
double real, double imag;
public:
Complex(double r, double i=0);
};
Complex::Complex(double r, double i){
real = r;
iamg = i;
}
Complex c1; //error, 缺少构造函数的参数
Complex * pc = new Complex; //error, 没有参数
Complex c1(2); //OK
Complex c1(2, 4), c2(3, 5); //OK
Complex * pc = new Complex(3, 4); //OK
- 构造函数在数组中的使用
class CSample{
int x;
public:
CSample(){
cout<<"Constructor 1 Called"<<endl;
}
CSample(int n){
x = n;
cout<<"Construcor 2 called"<<endl;
}
};
int main()
{
CSample array1[2];
cout<<"step1"<<endl; //输出Constructor 1 Called,Constructor 1 Called,step1
CSample array2[2]={4, 5};
cout<<"step2"<<endl; //输出输出Constructor 2 Called,Constructor 2 Called,step2
CSample array3[2]={3};
cout<<"step3"<<endl; //输出输出Constructor 2 Called,Constructor 1 Called,step3
CSample * array4 = new CSample[2];
delete []array4; //输出输出Constructor 1 Called,Constructor 1 Called
return 0;
}
class Test
{
public:
Test(int n) {} //(1)
Test(int n, int m) {} //(2)
Test() {} //(3)
};
Test array1[3] = {1, Test(1, 2)};
//三个元素分别用(1)、(2)、(3)初始化
Test array2[3] = {Test(2, 3), Test(1, 2), 1};
//三个元素分别用(2)、(2)、(1)初始化
Test * pArray[3] = {new Test(4), new Test(1, 2)}; //注意是指针对象数组,只有new才生成对象
//两个元素分别用(1)、(2)
第二课——复制构造函数
只有一个参数,同类对象的引用
如果没有定义复制构造函数,则编译器生成默认的复制构造函数。如果自定义复制构造函数,则默认的复制构造函数不存在。
- 复制构造函数起作用的三种情况:
(1)当用一个对象去初始化同类的另一个对象时;
Complex c2(c1);
Complex c2 = c1; //初始化,不是赋值
(2)某函数的一个参数是类A的对象,则参数被调用时,A的复制构造函数也被调用;
(3)某函数的返回值是类A的对象,则函数返回时,A的复制构造函数被调用;
第二课——类型转换构造函数
class Complex
{
public:
double real, imag;
Complex(int i)
{
cout<<"IntConstructor called"<<endl;
}
Complex(double r, double i)
{
real = r;
imag = i;
}
};
int main()
{
Cmplex c1(7, 8); //调用构造函数
Complex c2 = 12; //“=”是初始化,不是赋值;调用类型转换构造函数,且不生成临时对象
c1 = 9; //9被自动转化成一个临时Complex对象
return 0;
}
第二课——析构函数
一个类最多有一个析构函数
如果没有自定义析构函数,则编译器生成缺省析构函数,但是不涉及释放用户申请的内存释放等清理工作。
- 析构函数和对象数组
对象数组声明周期结束时:对象数组的每个元素的析构函数都会被调用。
- 析构函数和构造函数调用时机
class Demo
{
int id;
public:
Demo( int i)
{
id = i;
cout<<"id ="<<id<<" Constructed"<<endl;
}
~Demo()
{
cout<<"id ="<<id<<" Destructed"<<endl;
}
};
Demo d1(1); //全局变量 //输出:id=1 Constructed
void Func()
{
static Demo d2(2);
Demo d3(3);
cout<<"Func"<<endl;
}
int main()
{
Demo d4(4); //局部变量 //输出:id=4 Constructed
d4 = 6; //类型转换构造函数,临时对象 //输出:id=6 Constructed;id=6 Destructed
cout<<"main"<<endl; //输出:main
{ DEmo d5(5); } //作用域 //输出:id=5 Constructed;id=5 Destructed
Func(); //输出:id=2 Constructed;id=3 Constructed;Func; id=3 Destructed
cout<<"main ends"<<endl; //输出:main ends
return 0; //输出:id=6 Destructed;id=2 Destructed;id=1 Destructed
}