第十章 C++编程之构造顺序
10.1 解释概念
简单说,构造函数就是在定义某个类的时候会调用的一个函数,默认构造不带参,其余构造函数可以自己实现。
10.2 示例代码
1、示例代码
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Animal{
private:
int age;
char *name;
public:
//构造函数
Animal(){
cout << "1\Animal()" << endl;
age = 0;
name = NULL;
}
Animal(char*name,int age){
cout << "2\Animal(int age,char*name)" << endl;
cout << "my name is " << name << ",age is " << age << endl;
this->age = age;
this->name = new char[strlen(name)+1];
stpcpy(this->name,name);
}
//析构函数
~Animal(){
cout << "3\~Animal()" << endl;
cout << "my name is " << name << ",age is " << age << endl;
if(this->name!=NULL)
delete this->name;
}
void setAge(int age)
{
if(age<0)
age=0;
this->age = age;
}
void setName(char *name)
{
if(this->name!=NULL)
delete this->name;
this->name = new char[strlen(name)+1];
stpcpy(this->name,name);
}
void printInfo(void)
{
cout << "my name is " << name << ",age is " << age << endl;
}
};
//全局
Animal rabit("rabit:zhudi",5);
//静态全局
static Animal cat("cat : black",15);
void func(void)
{
//2、局部变量-lion
Animal lion("lion:xinba",2);
//3、局部静态变量 - monkey
static Animal monkey("monkey:wukong",20);
}
int main(int argc ,char**argv)
{
Animal tiger("tiger:daoba",10);
func();
Animal fox("fox:nike",9);
func();
cout << "-----------------------" << endl;
}
2、编译执行输出
2Animal(int age,char*name)
my name is rabit:zhudi,age is 5
2Animal(int age,char*name)
my name is cat : black,age is 15
2Animal(int age,char*name)
my name is tiger:daoba,age is 10
2Animal(int age,char*name)
my name is lion:xinba,age is 2
2Animal(int age,char*name)
my name is monkey:wukong,age is 20
3~Animal()
my name is lion:xinba,age is 2
2Animal(int age,char*name)
my name is fox:nike,age is 9
2Animal(int age,char*name)
my name is lion:xinba,age is 2
3~Animal()
my name is lion:xinba,age is 2
-----------------------
3~Animal()
my name is fox:nike,age is 9
3~Animal()
my name is tiger:daoba,age is 10
3~Animal()
my name is monkey:wukong,age is 20
3~Animal()
my name is cat : black,age is 15
3~Animal()
my name is rabit:zhudi,age is 5
10.3 构造和析构顺序总结
构造顺序如下:
1、全局变量,根据定义顺序构造
2、局部变量根据定义顺序进行够,静态局部变量只构造一次
析构顺序如下:
1、局部变量
2、局部静态变量
3、全局变量(定义顺序的逆序)
总结:
构造和析构函数的执行类似栈的方式,先进后出。