02 -- C++核心编程

02 -- C++核心编程


作者:elfin   资料来源:黑马程序员



	本阶段主要针对C++==面向对象==编程技术做详细讲解,探讨C++中的核心与精髓。

1、内存分区模型

C++程序在执行时,将内存大致划分为4个区域

  • 代码区:存放函数体的二进制代码,由操作系统进行管理;
  • 全局区:存放全局变量、静态变量以及常量;
  • 栈区:由编译器自动分配和释放,存放函数的参数值、局部变量等;
  • 堆区:有程序员分配和释放,若程序员不释放,程序结束时由OS回收。

内存四区的意义:

不同区域存放的数据,赋予不同的生命周期,给我们更大的灵活度。

1.1 程序运行前(代码区、全局区)

在程序编译后,生成了可执行程序,未执行该程序前分为两个区域

1.1.1 代码区

	存放CPU执行的机器指令

	代码区是**共享**的,共享的目的是对于频繁被执行的程序,只需要在内存中有一份代码即可

	代码区是**只读**的,使其只读的原因是防止程序意外地修改它的指令

1.1.2 全局区

	全局变量和静态变量存放在此.

	全局区还包含了常量区,字符串常量和其他常量也存放在此.

	该区域的数据在程序结束后由操作系统释放.
  • 全局区的演示代码

    #include <iostream>
    #include <string>
    using namespace std;
    
    //全局变量
    int g_a = 10;
    int g_b = 10;
    
    // const 修饰的全局常量
    const int c_g_a = 10;
    const int c_g_b = 10;
    
    int main()
    {
    	// 全局区
    	// 全局变量、静态变量、常量
    
    	// 创建普通局部变量
    	int a = 10;
    	int b = 10;
    	cout << "局部变量a的地址:" << (int)&a << endl;
    	cout << "局部变量b的地址:" << (int)&b << endl;
    
    	// 全局变量
    	cout << "全局变量g_a的地址:" << (int)&g_a << endl;
    	cout << "全局变量g_b的地址:" << (int)&g_b << endl;
    
    	// 静态变量
    	static int s_a = 10;
    	static int s_b = 10;
    	cout << "静态变量s_a的地址:" << (int)&s_a << endl;
    	cout << "静态变量s_b的地址:" << (int)&s_b << endl;
    
    	// 常量
    	// 字符串常量、const修饰的常量
    	// 字符串常量
    	cout << "字符串常量 hello 的地址:       " << (int)&"hello" << endl;
    	// const 修饰的全局常量
    	cout << "const修饰的全局常量c_g_a的地址:" << (int)&c_g_a << endl;
    	cout << "const修饰的全局常量c_g_b的地址:" << (int)&c_g_b << endl;
    	// const修饰的局部常量
    	const int c_l_a = 10;
    	const int c_l_b = 10;
    	cout << "const修饰的局部常量c_l_a的地址:" << (int)&c_l_a << endl;
    	cout << "const修饰的局部常量c_l_b的地址:" << (int)&c_l_b << endl;
    	system("pause");
    	return 0;
    }
    

    实验结果:

    基于上面的论述可以进行下面的总结。

  • 全局区包含的数据类型


Top  ---  Bottom

1.2 程序运行后(栈区、堆区)

1.2.1 栈区

	由编译器自动分配释放,存放函数的参数值,局部变量等

	**注意事宜**:不要返回局部变量的地址,栈区开辟的数据由编译器自动释放!

示例

#include <iostream>
#include <string>
using namespace std;

// 栈区开辟的数据由编译器自动释放
// 栈区数据注意事项 --- 不要返回局部变量的地址

int* func1(int b) // 形参数据也会放在栈区
{
	b = 100;
	int a = 10; // 局部变量 存放在栈区,栈区的数据在函数执行完毕后自动释放
	return &a; // 返回局部变量的地址
}

int* func2()
{
	int a = 20;
	return &a;
}

int* func3(int* s)
{
	++*s; // 注意指针指向的值要自增,必须使用++在前的方式,不然会让指针指向其他内存地址!
	return s;
}

int main()
{
	int* p1 = func1(1);
	cout << *p1 << endl; // 第一次可以执行,执行完之后就释放了
	cout << *p1 << endl; // 第二次可以执行,但是内存已经释放了,打印了乱码
	
	// 如果手贱返回了局部变量的地址,我们可以将其赋值给其他变量多次使用吗?
	int* p2 = func2();
	int a = *p2; // 这里是可以将其值赋值给其他变量的,但是这里多了一步,很容易遗漏,所以根本不建议返回局部变量的地址
	cout << a << endl;
	cout << a << endl;

	// 形参是指针,就可以返回它的地址?其实没有必要,下面的代码仅供娱乐
	int b = 2;
	int* p3 = func3(&b);
	cout << *p3 << endl;
	cout << *p3 << endl;
	system("pause");
	return 0;
}

返回的结果:

10
16257084
20
20
3
3
请按任意键继续. . .

栈区总结:


Top  ---  Bottom

1.2.2 堆区

	由程序员分配释放,若程序员不释放,程序结束时由操作系统回收

	在C++中主要利用**new**在堆区开辟内存

关键字new

示例

#include <iostream>
#include <string>
using namespace std;

int* func()
{
	// 利用new关键字  可以将数据开辟到堆区
	// 指针 本质也是局部变量,放在栈上,指针保存的数据是放在堆区
	int* a = new int(10);
	return a;
}

int main()
{
	// 在堆区开辟数据
	int* p = func();
	cout << *p << endl;
	cout << *p << endl;
	system("pause");
	return 0;
}

Top  ---  Bottom

1.3 new操作符

	C++中利用**new**操作符在堆区开辟数据

	在堆区开辟的数据需要由程序员手动释放,释放利用操作符**==delete==**

	**<font color=blue>语法</font>**:`new 数据类型`

	利用new创建的数据,会返回该数据对应类型的指针!

示例

#include <iostream>
#include <string>
using namespace std;

// 1、new的基本语法
int* func()
{
	// 在堆区创建整型数据
	// new返回是 该数据类型的指针
	int* p = new int(10);
	return p;
}

void test01()
{
	int* p = func();
	cout << *p << endl;
	cout << *p << endl;
	cout << *p << endl;
	// 堆区的数据由程序员管理开辟和释放
	delete p;
	// 指针指向了一个释放后的内存空间,即我们没有申请的内存空间,所以此时指向是非法的
	// cout << *p << endl; // 这段代码会报错,说没有初始化内存,程序不能执行
}

void test02()
{
	// 创建长度为10的整型数组在堆区
	int* arr = new int[10]; // 10代表数组有10个元素

	for (int i = 0; i < 10; i++)
	{
		arr[i] = i + 10;
	}
	for (int i = 0; i < 10; i++)
	{
		cout << arr[i] << endl;
	}
	// 释放堆区数组
	// 释放数组的时候要加[]才可以
	delete[] arr;
}

int main()
{
	// 在堆区开辟数据
	test01();
	test02();
	system("pause");
	return 0;
}

delete释放数组的时候要加 [] 才可以


Top  ---  Bottom

1.4 内存分区总结


Top  ---  Bottom

2、引用

2.1 引用的基本使用

作用:给变量起别名

语法数据类型 &别名 = 原名

示例

#include <iostream>
#include <string>
using namespace std;

int main()
{
	// 引用基本语法
	// 数据类型  & 别名 = 原名

	int a = 10;
	// 创建引用
	int& b = a;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	b = 100;
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	system("pause");
	return 0;
}

案例输出:

a = 10
b = 10
a = 100
b = 100
请按任意键继续. . .

Top  ---  Bottom

2.2 引用注意事项

  • 引用必须初始化
  • 初始化后,不可以改变引用

示例

#include <iostream>
#include <string>
using namespace std;

int main()
{
	// 引用基本语法
	// 数据类型  & 别名 = 原名

	int a = 10;
	// 创建引用初始化
	int& b = a;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	// 初始化之后,不可以改变
	int c = 100;
	b = c;  // 赋值操作而不是改变引用
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	int d = 10;
	// int& b = d; // 运行报错
	system("pause");
	return 0;
}

Top  ---  Bottom

2.3 引用做函数参数

作用:函数参数时,可以利用引用的技术让形参修饰实参

优点:可以简化指针修改实参

示例

#include <iostream>
#include <string>
using namespace std;

// 交换函数

// 1、值传递
void mySwap01(int a, int b)
{
	int temp = a;
	a = b;
	b = temp;
	cout << "swap01 a = " << a << endl;
	cout << "swap01 b = " << b << endl;
}

// 2、地址传递
void mySwap02(int* a, int* b)
{
	int temp = *a;
	*a = *b;
	*b = temp;
	cout << "swap02 *a = " << *a << endl;
	cout << "swap02 *b = " << *b << endl;
}

// 3、引用传递
void mySwap03(int& a, int& b)
{
	int temp = a;
	a = b;
	b = temp;
	cout << "swap03 a = " << a << endl;
	cout << "swap03 b = " << b << endl;
}

int main()
{

	int a = 10;
	int b = 20;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	// 1、值传递
	mySwap01(a, b);
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	// 2、地址传递
	mySwap02(&a, &b);
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	// 3、引用传递
	mySwap03(a, b); // 引用传递形参也会修改实参
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	system("pause");
	return 0;
}

案例运行结果:

a = 10
b = 20
swap01 a = 20
swap01 b = 10
a = 10
b = 20
swap02 *a = 20
swap02 *b = 10
a = 20
b = 10
swap03 a = 10
swap03 b = 20
a = 10
b = 20
请按任意键继续. . .

总结:通过引用参数产生的效果同地址传递是一样的。引用语法更清楚简单。


Top  ---  Bottom

2.4 引用做函数返回值

作用:引用是可以作为函数的返回值存在的

注意:不要返回局部变量的引用

语法:函数调用作为左值

示例

#include <iostream>
#include <string>
using namespace std;

// 交换函数

// 1、值传递
void mySwap01(int a, int b)
{
	int temp = a;
	a = b;
	b = temp;
	cout << "swap01 a = " << a << endl;
	cout << "swap01 b = " << b << endl;
}

// 2、地址传递
void mySwap02(int* a, int* b)
{
	int temp = *a;
	*a = *b;
	*b = temp;
	cout << "swap02 *a = " << *a << endl;
	cout << "swap02 *b = " << *b << endl;
}

// 3、引用传递
void mySwap03(int& a, int& b)
{
	int temp = a;
	a = b;
	b = temp;
	cout << "swap03 a = " << a << endl;
	cout << "swap03 b = " << b << endl;
}

// 引用做函数的返回值
// 1、不要返回局部变量的引用
int& test01()
{
	int a = 10;
	return a;
}

// 2、函数的调用可以作为左值
int& test02()
{
	static int a = 10; // 静态变量
	return a;
}

int main()
{
	// 引用做函数的返回值
	// 1、不要返回局部变量的引用
	int& ref = test01();
	cout << "ref = " << ref << endl;
	cout << "ref = " << ref << endl; //内存已经释放,出现乱码

	// 2、函数的调用可以作为左值
	int& ref2 = test02();
	cout << "ref2 = " << ref2 << endl;
	cout << "ref2 = " << ref2 << endl;
	test02() = 1000; // 函数的返回是引用时,函数的调用可以作为左值
	cout << "ref2 = " << ref2 << endl;
	cout << " a   = " << ref2 << endl;
	system("pause");
	return 0;
}

案例运行结果:

ref = 10
ref = 2035993104
ref2 = 10
ref2 = 10
ref2 = 1000
 a   = 1000
请按任意键继续. . .

Top  ---  Bottom

2.5 引用的本质

本质:引用的本质在C++内部实现是一个指针常量

指针常量是指向不能更改的指针。

示例

// 引用,编译器发现是引用,转换为 int* const ref = &a;
void func(int& ref)
{
    ref = 100; // ref是引用,转换为*ref = 100
}

int main()
{
    int a = 10;
    
    // 自动转换为 int* const ref = &a; 指针常量是指针指向不可改;也说明为什么引用不可更改
    int& ref = a;
    ref = 20; // 内部发现ref是引用,自动帮我们转换为:  *ref = 20;
    cout << "a:" << a << endl;
    cout << "ref:" << ref << endl;
    
    func(a);
    return 0;
}

Top  ---  Bottom

2.6 常量引用

作用:常量引用主要用来修饰形参,防止误操作

在函数形参列表中,可以加const修饰形参,防止形参改变实参

示例

#include <iostream>
#include <string>
using namespace std;

// 打印数据函数
void showValue1(int& val)
{
	cout << "val = " << val << endl;
	val = 100;
}

// 打印数据函数
void showValue2(const int& val)
{
	// val = 100; // const 修饰后不可修改
	cout << "val = " << val << endl;
}

int main()
{
	// 常量引用
	// 使用场景:用来修饰形参,防止误操作
	int a = 10;
	// int& ref = 10; // 引用必须引一块合法的内存空间
	// 加上const之后 编译器将代码修改: int temp = 10; const int& ref = temp;
	const int& ref = 10;
	// ref = 20; // 不允许修改

	// 修饰形参防止误操作
	showValue1(a);
	cout << "a = " << a << endl;
	showValue2(a);

	system("pause");
	return 0;
}

案例运行结果:

val = 10
a = 100
val = 100
请按任意键继续. . .

Top  ---  Bottom

3、函数提高

3.1 函数默认参数

在C++中,函数的形参列表中的形参是可以有默认值的。

语法返回值类型 函数名(参数=默认值){}

示例

#include <iostream>
#include <string>
using namespace std;

int func(int a, int b = 10, int c = 10)
{
    return a + b + c;
}

// 1.如果某个位置参数有默认值,那么从这个位置往后,从左向右,必须都要有默认值
// 2.如果函数声明有默认值,函数实现的时候就不能有默认参数
int func2(int a = 10, int b = 10);
int func2(int a, int b)
{
    return a + b;
}

int main()
{
    cout << func(10, 20, 30) << endl;
    cout << func(10, 20) << endl;
    cout << func2(10, 20) << endl;
    system("pause");
    return 0;
}

Top  ---  Bottom

3.2 函数占位参数

C++中函数的形参列表例可以有占位参数,用来做占位,调用函数时必须填补该位置

语法返回值类型 函数名(数据类型){}

在现阶段函数的占位参数存在意义不大,但是后面的课程中会用到该技术。

示例

#include <iostream>
#include <string>
using namespace std;

// 占位参数
// 返回值类型  函数名(数据类型){}
// 占位参数 还可以有默认参数
void func(int a, int =10)
{
    cout << "this is func" << endl;
}

int main()
{
    func(1, 10);
    system("pause");
    return 0;
}

Top  ---  Bottom

3.3 函数重载

3.3.1 函数重载概述

作用:函数名可以相同,提高复用性

函数重载需要满足条件:

  • 同一个作用域下
  • 函数名称相同
  • 函数参数类型不同 或者 个数不同 或者 顺序不同

注意:函数的返回值不可以作为函数重载的条件

示例

#include <iostream>
#include <string>
using namespace std;

// 函数重载
// 可以让函数名相同,提高复用性

// 函数重载的满足条件
// 同一个作用域下
// 函数名称相同
// 函数参数   类型不同  或者  个数不同  或者  顺序不同
void func()
{
    cout << "this is func" << endl;
}

void func(int a)
{
    cout << "this is func !" << endl;
}

int main()
{
    func();
    func(1);
    system("pause");
    return 0;
}

Top  ---  Bottom

3.3.2 函数重载注意事项

  • 引用作为重载条件
  • 函数重载碰到函数默认参数

示例

#include <iostream>
#include <string>
using namespace std;

// 函数重载的注意事项
// 1、引用作为重载的条件
void func(int& a)
{
    cout << "func(int &a)调用" << endl;
}

void func(const int& a)
{
    cout << "func(const int &a)调用" << endl;
}

// 2、函数重载碰到默认参数
int func2(int a, int b = 10)
{
    cout << "func2(int a)的调用" << endl;
}

int func2(int a)
{
    cout << "func2(int a)的调用" << endl;
}

int main()
{
    int a = 10;
    func(a);
    const int b = 20;
    func(b);
    func(10);

    // 2、函数重载碰到默认参数
    // func2(2); // 会报错,因为重载的两个函数都满足,尽量避免这种情况

    system("pause");
    return 0;
}

Top  ---  Bottom

4、类和对象

C++面向对象的三大特性为:封装、继承、多态

C++认为万物皆为对象,对象上有其属性和行为

4.1 封装

4.1.1 封装的意义

封装是C++面向对象三大特性之一

封装的意义一:

  • 将属性和行为作为一个整体,表现生活中的事物
  • 将属性和行为加以权限控制

示例

#include <iostream>
using namespace std;

// 圆周率
const double PAI = 3.14;

// 设计一个园类
class Circle
{
	// 访问权限
public:
	// 属性
	int m_r;

	// 行为
	double calculateZC()
	{
		return 2 * PAI * m_r;
	}
};

int main()
{
	Circle c1;
	c1.m_r = 3;

	cout << "周长:" <<c1.calculateZC() << endl;

	system("pause");
	return 0;
}

封装的意义二:

类在设计时,可以把属性和行为放在不同的权限下,加以控制

访问权限有三种:

  • 1、public 公共权限 成员类内可以访问,类外可以访问
  • 2、protected 保护权限 类外不能访问,但是子类可以访问
  • 3、private 私有权限 类外不能访问,子类也不能

示例

#include <iostream>
using namespace std;

class Student
{
private:
	string s_name;
	int s_age;
public:
	void setName(string name)
	{
		s_name = name;
	}
	void setAge(int age)
	{
		s_age = age;
	}
	void showName()
	{
		cout << "对象的名字:" << s_name << endl;
	}
	void showAge()
	{
		cout << "对象的年龄:" << s_age << endl;
	}
};

int main()
{
	Student s1;
	s1.setName("elfin");
	s1.setAge(12);
	s1.showName();
	s1.showAge();

	system("pause");
	return 0;
}

Top  ---  Bottom

4.1.2 struct和class的区别

在C++中,struct和class唯一的区别就在于 默认的访问权限不同

区别:

  • struct默认权限为公共
  • class默认权限为私有

Top  ---  Bottom

4.1.3 成员属性私有化

优点1:将所有成员属性设置为私有,可以自己控制读写权限

优点2:对于写权限,我们可以检测数据的有效性

案例参考4.1.1。


Top  ---  Bottom

4.2 对象的初始化和清理

4.2.1 构造函数和析构函数

对象的初始化清理也是两个非常重要的安全问题

  • 一个对象或者变量没有初始状态,对其使用后果是未知
  • 同样的使用完一个对象或变量,没有及时清理,也会造成一定的安全问题

C++利用了函数构造析构函数解决上诉问题,这两个函数将会被编译器自动调用,完成对象初始化和清理工作。

对象的初始化和清理工作是编译器强制我们要做的事情,因此如果我们不提供构造和析构,编译器会提供

编译器提供的构造函数和析构函数是空实现

  • 构造函数:主要作用在于创建对象时为对象的成员属性赋值,构造函数由编译器自动调用,无须手动调用。
  • 析构函数:主要作用在于对象销毁前系统自动调用,执行一些清理工作。

构造函数语法:

类名(){}

  • 1、构造函数,没有返回值也不写void;
  • 2、函数名称和类名相同;
  • 3、构造函数有参数,因此可以发生重载;
  • 4、程序在调用对象时会自动调用构造,无需手动调用,而且只会调用一次。

示例

#include <iostream>
using namespace std;

class Student
{
private:
	string s_name;
protected:
	int s_age;
public:
	void setName(string name)
	{
		s_name = name;
	}
	void setAge(int age)
	{
		s_age = age;
	}
	void showName()
	{
		cout << "对象的名字:" << s_name << endl;
	}
	void showAge()
	{
		cout << "对象的年龄:" << s_age << endl;
	}
	// 构造函数
	// 1、构造函数,没有返回值也不写void
	// 2、函数名称和类名相同
	// 3、构造函数有参数,因此可以发生重载
	// 4、程序在调用对象时会自动调用构造,无需手动调用,而且只会调用一次
	Student()
	{
		s_age = 18;
		cout << "您正在使用Student对象" << endl;
	}
};

int main()
{
	Student s1;
	s1.setName("elfin");
	s1.setAge(12);
	s1.showName();
	s1.showAge();

	system("pause");
	return 0;
}

运行结果:

您正在使用Student对象
对象的名字:elfin
对象的年龄:12
请按任意键继续. . .

析构函数语法:

~类名(){}

  • 1、析构函数,没有返回值也不写void;
  • 2、函数名称与类名相同,在名称前加上符号 ~;
  • 3、析构函数不可以有参数,因此不可以发生重载;
  • 4、程序在对象销毁前会自动调用析构,无需手动调用,而且只会调用一次。

示例

#include <iostream>
using namespace std;

class Student
{
private:
	string s_name;
protected:
	int s_age;
public:
	void setName(string name)
	{
		s_name = name;
	}
	void setAge(int age)
	{
		s_age = age;
	}
	void showName()
	{
		cout << "对象的名字:" << s_name << endl;
	}
	void showAge()
	{
		cout << "对象的年龄:" << s_age << endl;
	}
	// 构造函数
	// 1、构造函数,没有返回值也不写void
	// 2、函数名称和类名相同
	// 3、构造函数有参数,因此可以发生重载
	// 4、程序在调用对象时会自动调用构造,无需手动调用,而且只会调用一次
	Student()
	{
		s_age = 18;
		cout << "您正在使用Student对象" << endl;
	}

	// 析构函数
	// 1、析构函数,没有返回值也不写void
	// 2、函数名称与类名相同,在名称前加上符号 ~
	// 3、析构函数不可以有参数,因此不可以发生重载
	// 4、程序在对象销毁前会自动调用析构,无需手动调用,而且只会调用一次
	~Student()
	{
		cout << "您正在销毁Student对象" << endl;
	}
};

int main()
{
	Student s1;
	s1.setName("elfin");
	s1.setAge(12);
	s1.showName();
	s1.showAge();

	system("pause");
	return 0;
}

运行结果:

您正在使用Student对象
对象的名字:elfin
对象的年龄:12
请按任意键继续. . .
您正在销毁Student对象

Top  ---  Bottom

4.2.2 构造函数的分类及调用

两种分类方式:

  • 按参数分为:有参构造和无参构造
  • 按类型分为:普通构造和拷贝构造

三种调用方式:

  • 括号法
  • 显示法
  • 隐式转换法

示例

#include <iostream>
using namespace std;

class Student
{
public:
	int s_age;
public:
	// 构造函数
	Student()
	{
		s_age = 18;
		cout << "您正在使用Student的无参构造函数" << endl;
	}
	Student(int a)
	{
		s_age = a;
		cout << "您正在使用Student的有参构造函数" << endl;
	}
	// 拷贝构造函数
	Student(const Student &p)
	{
		s_age = p.s_age;
		cout << "您正在使用Student的拷贝构造函数" << endl;
	}

	~Student()
	{
		cout << "您正在销毁Student对象" << endl;
	}
};

int main()
{
	// 调用
	// 1、括号法
	Student s1;  // 默认构造函数调用
	s1.s_age = 20;
	Student s2(s1);  // 括号法调用 拷贝构造函数
	cout << "拷贝构造函数:对象的s_age:" << s2.s_age << endl;
	cout << "括号法调用结束" << endl;
	// 2、显示法
	Student s3;
	Student s4 = Student(14);  // 有参构造 
	Student s5 = Student(s4);// 拷贝构造函数调用
	// Student(14)是匿名对象,特点:当前行执行结束后,系统会立即回收掉匿名对象
	cout << "显示法调用结束" << endl;
	// 隐式转换法
	Student s6 = 10; // 相当于 写了 Student s6 = Student(10);
	Student s7 = s6; // 相当于 写了 Student s7 = Student(s6);
	system("pause");
	return 0;
}

运行结果:

您正在使用Student的无参构造函数
您正在使用Student的拷贝构造函数
拷贝构造函数:对象的s_age:20
括号法调用结束
您正在使用Student的无参构造函数
您正在使用Student的有参构造函数
您正在使用Student的拷贝构造函数
显示法调用结束
您正在使用Student的有参构造函数
您正在使用Student的拷贝构造函数
请按任意键继续. . .
您正在销毁Student对象
您正在销毁Student对象
您正在销毁Student对象
您正在销毁Student对象
您正在销毁Student对象
您正在销毁Student对象
您正在销毁Student对象

Top  ---  Bottom

4.2.3 拷贝机制调用时机

C++中拷贝构造函数调用时机通常有三种情况:

  • 使用一个已经创建完毕的对象来初始化一个新对象
  • 值传递的方式给函数参数传值
  • 以值方式返回局部对象
#include <iostream>
using namespace std;

class Student
{
public:
	int s_age;
public:
	// 构造函数
	Student()
	{
		s_age = 18;
		cout << "您正在使用Student的无参构造函数" << endl;
	}
	Student(int a)
	{
		s_age = a;
		cout << "您正在使用Student的有参构造函数" << endl;
	}
	// 拷贝构造函数
	Student(const Student& p)
	{
		s_age = p.s_age;
		cout << "您正在使用Student的拷贝构造函数" << endl;
	}

	~Student()
	{
		cout << "您正在销毁Student对象" << endl;
	}
};

// 1、使用一个已经创建完毕的对象来初始化一个新对象
void test()
{
	Student p1(20);
	Student p2(p1);
	cout << "p2的年龄为:" << p2.s_age << endl;
}

void doWork(Student p)
{

}

// 2、值传递的方式给函数参数传值
void test2()
{
	Student p1;
	doWork(p1);
}

// 3、以值方式返回局部对象
Student test3()
{
	Student p1;
	return p1;
}

int main()
{
	test();
	cout << "\n开始执行test2" << endl;
	test2();
	cout << "\n开始执行test3" << endl;
	test3();
	system("pause");
	return 0;
}

运行结果:

您正在使用Student的有参构造函数
您正在使用Student的拷贝构造函数
p2的年龄为:20
您正在销毁Student对象
您正在销毁Student对象

开始执行test2
您正在使用Student的无参构造函数
您正在使用Student的拷贝构造函数
您正在销毁Student对象
您正在销毁Student对象

开始执行test3
您正在使用Student的无参构造函数
您正在使用Student的拷贝构造函数
您正在销毁Student对象
您正在销毁Student对象
请按任意键继续. . .

Top  ---  Bottom

4.2.4 构造函数调用规则

默认情况下,C++编译器至少给一个类添加3个函数

  • 1、默认构造函数(无参,函数体为空)
  • 2、默认析构函数(无参,函数体为空)
  • 3、默认拷贝构造函数,对属性进行值拷贝

构造函数调用规则如下:

  • 如果用户定义有参构造函数,C++不再提供默认无参构造,但是会提供默认拷贝构造
  • 如果用户定义拷贝构造函数,C++不会再提供其他构造函数

示例1

#include <iostream>
#include <string>
using namespace std;

// 默认情况下,C++编译器至少给一个类添加3个函数
// 1、 默认构造函数(无参,函数体为空)
// 2、 默认析构函数(无参,函数体为空)
// 3、 默认拷贝构造函数,对属性进行值拷贝

class Student
{
public:
	int s_age = 12;

	Student()
	{
		cout << "默认构造函数调用" << endl;
	}

	Student(int a)
	{
		s_age = a;
		cout << "有参构造函数调用" << endl;
	}

	~Student()
	{
		cout << "默认析构函数调用" << endl;
	}
};

void test()
{
	Student s1;
	s1.s_age = 18;
	Student s2(s1);
	cout << "s2的年龄为:" << s2.s_age << endl;
}

int main()
{
	test();
	system("pause");
	return 0;
}

总结1:当前案例没有书写拷贝构造函数,但是这里仍然使用了拷贝构造函数,因为s2复制了s1的年龄。

示例2:如果写了有参构造编译器就不会自动不全默认无参构造

#include <iostream>
#include <string>
using namespace std;

// 默认情况下,C++编译器至少给一个类添加3个函数
// 1、 默认构造函数(无参,函数体为空)
// 2、 默认析构函数(无参,函数体为空)
// 3、 默认拷贝构造函数,对属性进行值拷贝

class Student
{
public:
	int s_age = 12;

	Student(int a)
	{
		s_age = a;
		cout << "有参构造函数调用" << endl;
	}

	~Student()
	{
		cout << "默认析构函数调用" << endl;
	}
};


void test2()
{
	// Student s1; // 实例初始化报错了,因为没有默认无参构造函数
	Student s1(25);
	Student s2(s1);
	cout << "s2的年龄为:" << s2.s_age << endl;
}

int main()
{
	test2();
	system("pause");
	return 0;
}

总结1:当前案例书写有参构造函数时,编译器会补全拷贝构造函数,但是不会提供无参构造函数。


Top  ---  Bottom

4.2.5 深拷贝和浅拷贝

深浅拷贝是面试的经典问题,也是常见的一个坑

浅拷贝:简单的赋值拷贝操作

深拷贝:在堆区重新申请空间,进行拷贝操作

错误示例

#include <iostream>
#include <string>
using namespace std;

class Student
{
public:
	int s_age = 12;
	int* s_height;

	Student()
	{
		s_height = new int(165);
		cout << "默认构造函数调用" << endl;
	}

	Student(int a, int height)
	{
		s_age = a;
		s_height = new int(height);
		cout << "有参构造函数调用" << endl;
	}

	~Student()
	{
		// 析构代码,将堆区的数据做释放
		if (s_height != NULL)
		{
			// 此时在使用拷贝构造函数时,会进行浅拷贝操作,这里是个指针,存放的是地址,
			// 如果两个对象是拷贝产生的,那么一个对象的此指针和另一个代码是一模一样的,
			// 删除时,第一个被复制的对象释放时,此指针已经不存在了,就会报错!
			delete s_height; 
			s_height = NULL;
		}
		cout << "默认析构函数调用" << endl;
	}
};

void test()
{
	Student s1(18,175);
	cout << "s1的年龄为:" << s1.s_age << "\ts1的身高为:" << *s1.s_height << endl;
	Student s2(s1);
	cout << "s2的年龄为:" << s2.s_age << "\ts2的身高为:" << *s2.s_height << endl;
}


int main()
{
	test();
	system("pause");
	return 0;
}

自己书写一个拷贝构造函数,解决浅拷贝带来的释放冲突的问题。

示例

#include <iostream>
#include <string>
using namespace std;

class Student
{
public:
	int s_age = 12;
	int* s_height;

	Student()
	{
		s_height = new int(165);
		cout << "默认构造函数调用" << endl;
	}

	Student(int a, int height)
	{
		s_age = a;
		s_height = new int(height);
		cout << "有参构造函数调用" << endl;
	}

	Student(Student &s)
	{
		s_age = s.s_age;
		//s_height = s.s_height; // 编译器的默认实现
		s_height = new int(*s.s_height);
		cout << "拷贝构造函数调用" << endl;
	}

	~Student()
	{
		// 析构代码,将堆区的数据做释放
		if (s_height != NULL)
		{
			delete s_height; 
			s_height = NULL;
		}
		cout << "默认析构函数调用" << endl;
	}
};

void test()
{
	Student s1(18,175);
	cout << "s1的年龄为:" << s1.s_age << "\ts1的身高为:" << *s1.s_height << endl;
	Student s2(s1);
	cout << "s2的年龄为:" << s2.s_age << "\ts2的身高为:" << *s2.s_height << endl;
}


int main()
{
	test();
	system("pause");
	return 0;
}

Top  ---  Bottom

4.2.6 初始化列表

作用:C++提供了初始化列表语法,用来初始化属性

语法构造函数():属性1(值1), 属性2(值2)… {}

示例

#include <iostream>
#include <string>
using namespace std;

// 初始化属性列表

class Student
{
public:
	int s_age;
	int s_height;

	// 初始化列表初始化属性
	Student(int age, int height): s_age(age), s_height(height)
	{
		cout << "默认构造函数调用" << endl;
	}

	//// 传统初始化操作
	//Student(int a, int height)
	//{
	//	s_age = a;
	//	s_height = height;
	//	cout << "有参构造函数调用" << endl;
	//}


	~Student()
	{
		cout << "默认析构函数调用" << endl;
	}
};

void test()
{
	Student s1(18, 175);
	cout << "s1的年龄为:" << s1.s_age << "\ts1的身高为:" << s1.s_height << endl;
	Student s2(s1);
	cout << "s2的年龄为:" << s2.s_age << "\ts2的身高为:" << s2.s_height << endl;
}


int main()
{
	test();
	system("pause");
	return 0;
}

Top  ---  Bottom

4.2.7 类对象作为类成员

C++类中的成员是另一个类的对象,我们把该成员称之为 对象成员

示例

class A{}
class B
{
    A a;
}

B类中有对象A作为成员,A为对象成员

那么当创建B对象时,A与B的构造和析构的顺序是谁先谁后?

答案:A先构造,A后析构。析构顺序与构造顺序相反!


Top  ---  Bottom

4.2.8 静态成员

静态成员就是成员变量和成员函数前加上了关键字static,称之为静态成员

静态成员分为:

  • 静态成员变量
    • 所有对象共享同一份数据
    • 在编译阶段分配内存
    • 类内声明,类外初始化
  • 静态成员函数(有权限的,即可以设置访问权限)
    • 所有对象共享同一个函数
    • 静态成员函数只能访问静态成员变量

示例1:静态成员变量

#include <iostream>
#include <string>
using namespace std;

// 静态成员函数
// 所有对象共享同一个函数
// 静态成员函数只能访问静态成员变量


class Student
{
public:
	static int s_age; // 静态成员变量
	int s_height; // 非静态成员变量

	// 静态成员函数
	static void func()
	{
		s_age = 20; // 静态成员函数可以访问 静态成员变量
		//s_height = 200; // 修改非静态成员变量报错
		cout << "static void func 调用" << endl;
	}
	

};

int Student::s_age = 18;

void test()
{
	// 1、通过对象访问
	Student s1;
	s1.func();
	// 2、通过类名访问
	Student::func();
}


int main()
{
	test();
	system("pause");
	return 0;
}

Top  ---  Bottom

4.3 C++对象模型和this指针

4.3.1 成员变量和成员函数分开存储

在C++中,类内的成员变量和成员函数分开存储

只有非静态成员变量才属于类的对象上

示例1:空对象

#include <iostream>
#include <string>
using namespace std;

// 成员变量和成员函数分开存储
class Student
{
};

void test()
{
	Student s1;
	cout << "创建一个空Studen对象所占的内存空间:" << sizeof(s1) << endl;
	
}

int main()
{
	test();
	system("pause");
	return 0;
}

运行结果:

创建一个空Studen对象所占的内存空间:1
请按任意键继续. . .

空对象为什么是1,这是因为C++编译器会给每个空对象也分配一个字节空间,是为了区分空对象占内存的位置。每个空对象也应该有一个独一无二的空间。

示例2:仅含非静态成员变量

#include <iostream>
#include <string>
using namespace std;

// 成员变量和成员函数分开存储


class Student
{
	int age = 10; // 非静态成员变量
};

void test()
{
	Student s1;
	cout << "创建一个含有非静态成员变量Studen对象所占的内存空间:" << sizeof(s1) << endl;
}


int main()
{
	test();
	system("pause");
	return 0;
}

运行结果:

创建一个含有非静态成员变量Studen对象所占的内存空间:4
请按任意键继续. . .

这里已经不是空对象类,就分配类int所占的内存空间大小!

示例3:只有非静态成员变量属于类对象的存储空间

#include <iostream>
#include <string>
using namespace std;

// 成员变量和成员函数分开存储


class Student
{
	int age = 10; // 非静态成员变量       属于类对象的存储空间
	static int height; // 静态成员变量    不属于类对象的存储空间
	void func(){} // 非静态成员函数       不属于类对象的存储空间
	static void func2(){} // 静态成员函数 不属于类对象的存储空间
};
int Student::height = 175;

void test()
{
	Student s1;
	cout << "Studen对象所占的内存空间:" << sizeof(s1) << endl;
	
}


int main()
{
	test();
	system("pause");
	return 0;
}

运行结果:

Studen对象所占的内存空间:4
请按任意键继续. . .

Top  ---  Bottom

4.3.2 this指针概念

通过4.3.1我们知道在C++成员变量和成员函数是分开存储的

每一个非静态成员函数只会诞生一份函数实例,也就是说多个同类型的对象会共用一块代码

那么问题是:这一块代码是如何区分是哪个对象调用自己的呢?

C++通过提供特殊的对象指针,this指针,解决上诉问题。this指针指向被调用的成员函数所属的对象

this指针是隐含每一个非静态成员函数内的一种指针

this指针不需要定义,直接可以使用

this指针的用途:

  • 当形参和成员变量同名时,可以使用this指针进行区分;
  • 在类的非静态成员函数中返回对象本身,可使用 return *this

示例

#include <iostream>
#include <string>
using namespace std;


class Student
{
public:
	int age;

	// 1、解决名称冲突
	Student(int age)
	{
		this->age = age;  // 形参和成员属性同名时,要使用this指针进行区分
	}

	// 2、返回对象本身,可使用   return *this
	Student& studentAddAge(Student &s)
	{
		this->age += s.age;
		return *this;
	}
};



void test()
{
	Student s1(15);
	Student s2(15);

	// 链式变成思想
	s2.studentAddAge(s1).studentAddAge(s1).studentAddAge(s1);
	cout << "s2的年龄为:" << s2.age << endl;

}


int main()
{
	test();
	system("pause");
	return 0;
}

注意事项:

s2.studentAddAge(s1).studentAddAge(s1).studentAddAge(s1);语句在调用时如果studentAddAge函数返回的不是引用,那么语句返回的也不是s2对象,即``s2.studentAddAge(s1)`会让年龄相加,但是这个语句返回的不是s2,所有后面的链式操作不会使s2有任何变化!也即若不是引用返回,最后输出的就是30。


Top  ---  Bottom

4.3.3 空指针访问成员函数

C++中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针

如果使用了this指针,需要加以判断保证代码的健壮性!

示例1:空指针访问成员属性

#include <iostream>
#include <string>
using namespace std;


class Student
{
public:
	int age;

	void showAge()
	{
		cout << "对象的年龄为:" << age << endl;
	}

	void showName()
	{
		cout << "对象的类名为:Student" << endl;
	}
};



void test()
{
	Student* s1 = NULL;
	s1->showName();
	s1->showAge(); // 报错,用到属性变量即报错了
}


int main()
{
	test();
	system("pause");
	return 0;
}

这里s1->showAge(); 报错了,因为空指针不能访问这些成员属性!,如果要能访问即需要进行控制了!

示例2:空指针访问成员属性

#include <iostream>
#include <string>
using namespace std;


class Student
{
public:
	int age;

	void showAge()
	{
		if (this == NULL)
		{
			return;
		}
		cout << "对象的年龄为:" << age << endl;
	}

	void showName()
	{
		cout << "对象的类名为:Student" << endl;
	}
};



void test()
{
	Student* s1 = NULL;
	s1->showName();
	s1->showAge(); // 报错,用到属性变量即报错了
}


int main()
{
	test();
	system("pause");
	return 0;
}

运行结果:

对象的类名为:Student
请按任意键继续. . .

Top  ---  Bottom

4.3.4 const修饰成员函数

常函数:

  • 成员函数后加const后我们称之为常函数
  • 常函数内不可以修改成员属性
  • 成员属性声明时加关键字mutable后,在常函数中依然可以修改

常对象:

  • 声明对象前加const称该对象为常对象
  • 常对象只能调用常函数

示例

#include <iostream>
#include <string>
using namespace std;


class Student
{
public:
	mutable int age; // 特殊变量,即使在常函数中,也可以修改这个值,加关键字mutable
	string s_name;

	// this指针的本质 是指针常量   指针的指向是不可以修改的
	// 如果要使this指向的值不能修改,则相当于:const Student* const this;
	// 在成员函数中,可以使用如下的方式实现:
	// const void showName() // 这种方式是没用的、没用的、没用的!
	// 在成员函数后面加const,修饰的是this指向,让指针指向的值也不可以修改
	void showName() const
	{
		//s_name = "elfin"; // 报错了
		//this->s_name = "elfin"; // 报错了
		this->age = 20;
		cout << "对象的类名为:" << s_name <<endl;
	}

	void func() {

	}
};



void test()
{
	Student s1;
	s1.showName();
}

void test2()
{
	const Student s2; // 在对象前加const,得到常对象
	s2.age = 100; // 使用mutable关键字修饰的属性可以修改
	//s2.s_name = "elfin"; // 报错了
	s2.showName();
	
	// 常对象只能调用常函数
	//s2.func(); // 报错了
	s2.showName();
}


int main()
{
	test();
	test2();
	system("pause");
	return 0;
}

Top  ---  Bottom

4.4 友元

生活之中你家有客厅(public),有你的卧室(private),都没有就赶紧争取买个厕所!

客厅所有的客人都可以进去,但是你的卧室是私有的,也就是说只有你能进去。

但是呢,你也可以允许你的好闺蜜进去。

在C++程序中,有些私有的属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术!

友元的目的就是让一个函数或者类访问另一个类中的私有成员

关键字friend

友元的三种实现:

  • 全局函数做友元;
  • 类做友元;
  • 成员函数做友元。

Top  ---  Bottom

4.4.1 全局函数做友元

#include <iostream>
#include <string>
using namespace std;

class Building
{
	// goodGay全局函数是Building好朋友,可以访问Building中私有成员
	friend void goodGay(Building* building);
public:
	string m_SittingRoom; // 客厅
private:
	string m_BedRoom; // 卧室
public:
	Building()
	{
		m_SittingRoom = "客厅";
		m_BedRoom = "卧室";
	}
};

// 全局函数
void goodGay(Building* building)
{
	cout << "好基友全局函数正在访问:" << building->m_SittingRoom << endl;
	// 访问私有属性必须使用友元
	cout << "好基友全局函数正在访问:" << building->m_BedRoom << endl;
}

void test()
{
	Building building;
	goodGay(&building);
}

int main()
{
	test();

	system("pause");
	return 0;
}

Top  ---  Bottom

4.4.2 类做友元

#include <iostream>
#include <string>
using namespace std;

// 类做友元
class Building;

class GoodGay
{
public:
	Building* building;

	void visit(); // 参观函数,要访问Building的共有成员、私有成员

	GoodGay();
};

class Building
{
	// GoodGay类是Building好朋友,可以访问Building中私有成员
	friend class GoodGay;
public:
	string m_SittingRoom; // 客厅
	Building();
private:
	string m_BedRoom; // 卧室

};

GoodGay::GoodGay()
{
	// 创建一个建筑物的对象
	building = new Building;
}

void GoodGay::visit()
{
	cout << "好基友类正在访问:" << building->m_SittingRoom << endl;
	// 访问私有属性必须使用友元
	cout << "好基友类正在访问:" << building->m_BedRoom << endl;
}

// 类外写成员函数
Building::Building()
{
	m_SittingRoom = "客厅";
	m_BedRoom = "卧室";
}


void test()
{
	GoodGay goodgay;
	goodgay.visit();
}

int main()
{
	test();

	system("pause");
	return 0;
}

Top  ---  Bottom

4.4.3 成员函数做友元

#include <iostream>
#include <string>
using namespace std;

// 类做友元
class Building;

class GoodGay
{
public:
	Building* building;

	void visit1(); // 参观函数,要访问Building的共有成员、私有成员
	void visit2(); // 不能访问Building的私有成员

	GoodGay();
};

class Building
{
	// GoodGay类是Building好朋友,可以访问Building中私有成员
	friend void GoodGay::visit1();
public:
	string m_SittingRoom; // 客厅
	Building();
private:
	string m_BedRoom; // 卧室

};

GoodGay::GoodGay()
{
	// 创建一个建筑物的对象
	building = new Building;
}

void GoodGay::visit1()
{
	cout << "好基友类的成员函数visit1正在访问:" << building->m_SittingRoom << endl;
	// 访问私有属性必须使用友元
	cout << "好基友类的成员函数visit1正在访问:" << building->m_BedRoom << endl;
}

void GoodGay::visit2()
{
	cout << "好基友类的成员函数visit2正在访问:" << building->m_SittingRoom << endl;
	// 访问私有属性必须使用友元
	// cout << "好基友类正在访问:" << building->m_BedRoom << endl;
}

// 类外写成员函数
Building::Building()
{
	m_SittingRoom = "客厅";
	m_BedRoom = "卧室";
}


void test()
{
	GoodGay goodgay;
	goodgay.visit1();
}

int main()
{
	test();

	system("pause");
	return 0;
}

Top  ---  Bottom

4.5 重载运算符

4.5.1 重载运算符“+”

成员函数实现加号运算符重载

#include <iostream>
#include <string>
using namespace std;


class Student
{
public:
	int s_age = 12;
	string s_name = "";
	int s_total = 0;

	Student()
	{
	}

	Student(int age, string name, int total);

	// 成员函数实现加号运算符重载
	Student operator+(Student& student1)
	{
		Student student2;
		student2.s_total = this->s_total + student1.s_total;
		student2.s_name = "";
		student2.s_name = student1.s_age;
		return student2;
	}
};

Student::Student(int age, string name, int total)
{
	s_age = age;
	s_name = name;
	s_total = total;
}

void test()
{
	Student s1;
	s1.s_age = 20;
	s1.s_name = "elfin";
	s1.s_total = 5;
	Student s2;
	s2.s_age = 18;
	s2.s_name = "dan";
	s2.s_total = 5;
	Student s3 = s1 + s2;
	cout << "s3 = s1 + s2 : " << s3.s_total  << endl;
}


int main()
{
	test();
	system("pause");
	return 0;
}

全局函数实现加号运算符重载

#include <iostream>
#include <string>
using namespace std;


class Student
{
public:
	int s_age = 12;
	string s_name = "";
	int s_total = 0;

	Student()
	{
	}

	Student(int age, string name, int total);
};

Student::Student(int age, string name, int total)
{
	s_age = age;
	s_name = name;
	s_total = total;
}

// 全局函数实现加号运算符重载
Student operator+(Student& student1, Student& student2)
{
	Student student;
	student.s_total = student1.s_total + student2.s_total;
	return student;
}

// 全局函数实现加号运算符重载
Student operator+(Student& student1, int student2)
{
	Student student;
	student.s_total = student1.s_total + student2;
	return student;
}


void test()
{
	Student s1;
	s1.s_age = 20;
	s1.s_name = "elfin";
	s1.s_total = 5;
	Student s2;
	s2.s_age = 18;
	s2.s_name = "dan";
	s2.s_total = 5;
	Student s3 = s1 + s2;
	cout << "s3 = s1 + s2 : " << s3.s_total << endl;
	Student s4 = s1 + 10;
	cout << "s4 = s1 + 10 : " << s4.s_total << endl;

}


int main()
{
	test();
	system("pause");
	return 0;
}


Top  ---  Bottom


Top  ---  Bottom

4.5.2 左移运算符重载

作用:可以输出自定义数据类型

示例

#include <iostream>
#include <string>
using namespace std;

class Person
{
public:
	int m_A;
	int m_B;
};

ostream& operator<<(ostream &cout, Person &son)
{
	cout << "m_A = " << son.m_A << " m_B = " << son.m_B << endl;
	return cout;
}

int main()
{
	Person son;
	son.m_A = 20;
	son.m_B = 5;
	cout << son << endl;
	system("pause");
	return 0;
}

Top  ---  Bottom

4.5.3 递增运算符++

#include <iostream>
#include <string>
using namespace std;

class Person
{
public:
	int m_A = 10;

	// 重载前置++运算符
	Person& operator++()
	{
		m_A++;
		return *this;
	}

	// 后置前置++运算符
	Person operator++(int)
	{
		Person temp = *this;
		m_A++;
		return temp;
	}
};

ostream& operator<<(ostream& cout, const Person& son)
{
	cout << "m_A = " << son.m_A << endl;
	return cout;
}

int main()
{
	Person son;
	son.m_A = 20;
	cout << "son初始化输出:\t" << son << endl;
	cout << "++son运算输出:\t" << ++son << endl;
	cout << "++(++son)输出:\t" << ++(++son) << endl;
	cout << "前置递增后输出:\t" << son << endl;
	cout << "(son++)++输出:\t" << (son++)++ << endl;
	cout << "后置递增后输出:\t" << son << endl;


	system("pause");
	return 0;
}

Top  ---  Bottom

4.5.4 赋值运算符重载

c++编译器至少给一个类添加4个函数

  • 默认构造函数(无参,函数体为空)
  • 默认析构函数(无参,函数体为空)
  • 默认拷贝函数,对属性进行值拷贝
  • 赋值运算符operator=,对属性进行值拷贝

如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题

示例

5、文件操作

作用

语法:``

示例



Top  ---  Bottom

完!

posted @ 2021-01-23 18:17  巴蜀秀才  阅读(101)  评论(0编辑  收藏  举报