1. C语言我们怎么编程的?
#include <stdlib.h>
struct example
{
int m_a;
char m_b;
};
void initialize(struct example * ptr)
{
if(ptr)
{
ptr->m_a = 0;
ptr->m_b = 'A';
}
}
int main(void)
{
struct example * pexample = (struct example *)malloc(sizeof(struct example));
initialize(pexample);
free(pexample);
return 0;
}
分配一段内存,然后调用一个initialize的函数,做些初始化工作!
观查操作系统内核代码,或者很多基于c的应用程序不难发现,他们都有这个编程特点
C++ 的设计思想,一般把初始化工作放在构造函数中来!
2. 考虑C++怎么优化的?
2.1 构造函数
构造函数负责为类实例化之后的初始化操作。
构造函数也是普通的成员函数,其特殊的地方在于简化了C++编程,构造函数由编译器自动调用
- 构造函数自动调用,构造函数不需要返回值
//constructor.cpp
#include <iostream>
using namespace std;
class Store {
public:
/*类Store的构造函数*/
Store (void)
{
/*构造函数用于初始化成员变量*/
fruits = 0;
weapons = 0;
cout << "我是构造函数" << endl;
}
int fruits;
int weapons;
};
int main(void)
{
/*这里编译器 自动调用构造函数*/
Store St1;
cout << St1.fruits << ' ' << St1.weapons << endl;
return 0;
}
2.2 构造函数可以重载
#include <iostream>
using namespace std;
class Store {
public:
/*无参构造函数,也叫缺省构造函数*/
Store (void)
{
fruits = 0;
weapons = 0;
cout << "我是缺省构造函数" << endl;
}
Store (int i)
{
fruits = i;
weapons = 0;
cout << "我是单参构造函数" << endl;
}
Store (int i, int j)
{
fruits = i;
weapons = j;
cout << "我是多参构造函数" << endl;
}
int fruits;
int weapons;
};
int main(void)
{
Store St1_void;
Store St2_int (99);
Store St3_int_int(99,99);
return 0;
}
输出:
this is construct void function
this is construct int function
this is construct int double function
2.3 特殊的构造函数,拷贝构造
#include <iostream>
using namespace std;
class Store {
public:
/*构造函数*/
Store (int fru, int wea)
{
cout << "我是多参数构造函数" << endl;
fruits = fru;
weapons = wea;
}
/*拷贝构造函数*/
Store (Store const& that)
{
cout << "我是拷贝构造函数" << endl;
fruits = that.fruits;
weapons = that.weapons;
}
int fruits;
int weapons;
};
int main(void)
{
/*随便实例化一个对象*/
Store St1(99,100);
cout << St1.fruits << ' ' << St1.weapons << endl;
/*用一个实例化过的对象St1 实例化St2,编译器自动调用拷贝构造函数*/
Store St2 (St1);
cout << St2.fruits << ' ' << St2.weapons << endl;
return 0;
}
输出:
this is construct function
99 100
copy fuction
99 100