C++核心编程

内存分区

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

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

//全局常量
const int cga = 34;
const int cgb = 657;

int main() {

	cout << "全局变量  " << (int) & g_a << endl;
	cout << "全局变量  " << (int)&g_b << endl;
	
	cout << "全局常量  " << (int)&cga << endl;
	cout << "全局常量  " << (int)&cgb << endl;
	
	//局部变量
	int a = 3435;
	int b = 31;
	cout << "局部变量:  " << (int)&a << endl;
	cout << "局部变量:  " << (int)&b << endl;
	
	//局部常量
	const int cgal = 34;
	const int cgbl = 657;
	cout << "局部常量:  " << (int)&cgal << endl;
	cout << "局部常量:  " << (int)&cgbl << endl;
	
	//静态变量
	static int sa = 34;
	static int sb = 34;
	cout << "静态常量:  " << (int)&sa << endl;
	cout << "静态常量:  " << (int)&sb << endl;
	
	cout << "字符串常量地址: " << (int)&"abddkfjd" << endl;
	cout << "字符串常量地址: " << (int)&"东方科技日俄" << endl;
全局变量  -1414745996
全局变量  -1414745992
全局常量  -1414763480
全局常量  -1414763476
局部变量:  640940500
局部变量:  640940532
局部常量:  640940564
局部常量:  640940596
静态常量:  -1414745988
静态常量:  -1414745984
字符串常量地址: -1414767072
字符串常量地址: -1414767056

栈区:

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

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

#include<iostream>
using namespace std;

int* fun1()
{
	int a = 23;
	return &a;
}


int main33() {

	int *p=fun1();
	cout << p << endl;
	cout << *p << endl;
	cout << p << endl;	
	cout << *p << endl;


	system("pause");
	return 0;
}
运行起来返回结果一样,视频的不一样
0000008FC479F574
23
0000008FC479F574
23

引用

引用的基本使用

**作用: **给变量起别名

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

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

​ //int &c; //错误,引用必须初始化

void mySwap(int& c, int& d)
{
	int a = c;
	c = d;
	d = a;
}

int main()
{

	int c = 343;
	int d = 4545;
	cout << "c:  " << c << "   d: " << d << endl;
	mySwap(c, d);	
	cout << "c:  " << c << "   d: " << d << endl;

system("pause");
return 0;

}
//1. 值传递
void mySwap01(int a, int b) {
	int temp = a;
	a = b;
	b = temp;
}

//2. 地址传递
void mySwap02(int* a, int* b) {
	int temp = *a;
	*a = *b;
	*b = temp;
}

//3. 引用传递
void mySwap03(int& a, int& b) {
	int temp = a;
	a = b;
	b = temp;
}

mySwap01(a, b);
cout << "a:" << a << " b:" << b << endl;

mySwap02(&a, &b);
cout << "a:" << a << " b:" << b << endl;

mySwap03(a, b);
cout << "a:" << a << " b:" << b << endl;

引用做函数返回值

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

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

用法:函数调用作为左值

int& test1()
{
	int a = 45;
	return a;

}
int& test2()
{
	static int a = 45;
	return a;

}
	int& ref1=test1();
	int& ref2=test2();
	cout << "ref1: " << ref1 << endl;
	cout << "ref1: " << ref1 << endl;
	cout << "ref2: " << ref2 << endl;
	cout << "ref2: " << ref2 << endl;

	test2() = 90;
	cout << "ref2: " << ref2 << endl;
	cout << "ref2: " << ref2 << endl;

ref1: 45
ref1: 2062326152
ref2: 45
ref2: 45
ref2: 90
ref2: 90

引用的本质

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

int * const p 指针常量

可以改值,不可以改地址

//发现是引用,转换为 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;

}

函数提高

函数默认参数

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

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

//1. 如果某个位置参数有默认值,那么从这个位置往后,从左向右,必须都要有默认值
//2. 如果函数声明有默认值,函数实现的时候就不能有默认参数

函数占位参数

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

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

//函数占位参数 ,占位参数也可以有默认参数
void func(int a, int) {
	cout << "this is func" << endl;
}



	func(10,10); //占位参数必须填补
函数重载概述

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

函数重载满足条件:

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

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

//函数重载需要函数都在同一个作用域下
void func()
{
	cout << "func 的调用!" << endl;
}
void func(int a)
{
	cout << "func (int a) 的调用!" << endl;
}
void func(double a)
{
	cout << "func (double a)的调用!" << endl;
}
void func(int a ,double b)
{
	cout << "func (int a ,double b) 的调用!" << endl;
}
void func(double a ,int b)
{
	cout << "func (double a ,int b)的调用!" << endl;
}
函数重载注意事项
  • 引用作为重载条件
  • 函数重载碰到函数默认参数
//函数重载注意事项
//1、引用作为重载条件

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

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


//2、函数重载碰到函数默认参数

void func2(int a, int b = 10)
{
	cout << "func2(int a, int b = 10) 调用" << endl;
}

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

int main() {
	
	int a = 10;
	func(a); //调用无const
	func(10);//调用有const  只能调用这个,10不能调用&a


	//func2(10); //碰到默认参数产生歧义,需要避免

	system("pause");

	return 0;
}

类和对象

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

在设计类的时候,属性和行为写在一起,表现事物

封装意义一:

语法: class 类名{ 访问权限: 属性 / 行为 };

//圆周率
const double PI = 3.14;

class Circle
{
public:
	double m_r;
	 
	double area(double  m_r)
	{
		return PI * m_r * m_r;
	} 
	double area()
	{
		return PI * m_r * m_r;
	}
};

int main()
{

	Circle c;
	c.m_r = 33;
	
	cout << "面积: " << c.area(10) << endl;
	cout << "面积: " << c.area() << endl;

	system("pause");
	return 0;
}
class Student
{
public:
	void setId(int nid)
	{
		id = nid;
	}
	void setName(string nname)
	{
		name = nname;
	}
	void showStudent() {
		cout << "name:  " << name << "  id:  " << id << endl;
	}

private:
	int id;
	string name;
};



int main()
{
	Student s;
	s.setId(34);
	s.setName("张三四");
	s.showStudent();

	system("pause");
	return 0;
}

封装意义二:

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

访问权限有三种:

  1. public 公共权限
  2. protected 保护权限
  3. private 私有权限
struct和class区别

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

区别:

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

练习案例1:设计立方体类

设计立方体类(Cube)

求出立方体的面积和体积

分别用全局函数和成员函数判断两个立方体是否相等。

练习案例2:点和圆的关系

设计一个圆形类(Circle),和一个点类(Point),计算点和圆的关系。

案例1 立方体类

#include<iostream>
using namespace std;

class Cube
{
public:
	void setL(int L)
	{
		m_L = L;
	}
	void setW(int W)
	{
		m_W = W;
	}
	void setH(int H)
	{
		m_H = H;
	}
	int getL()
	{
		return m_L;
	}
	int getW()
	{
		return m_W;
	}
	int getH()
	{
		return m_H;
	}
	int getArea()
	{
		return 2*(m_L * m_L + m_W * m_W + m_H * m_H);
	}
	int getVolume()
	{
		return m_L * m_W * m_H;
	}
	bool isSameByClass(Cube c)
	{
		return m_L == c.m_L && m_H == c.m_H && m_W == c.m_W;
	}

private:
	int m_L;
	int m_W;
	int m_H;
};
bool isSame(Cube c1, Cube c2)
{
	return c1.getH() == c2.getH() && c1.getL() == c2.getL() && c1.getW() == c2.getW();
}

int main()
{
	Cube c;
	c.setH(2);
	c.setW (2);
	c.setL(2);

	cout << "面积为:" << c.getArea() << endl;
	cout << "体积为: " << c.getVolume() << endl;
	
	Cube c2;
	c2.setH(2);
	c2.setW(4);
	c2.setL(2);

	cout << (c.isSameByClass(c2) ? "内部判断相等":"内部判断不相等") << endl;

	cout << (isSame(c,c2)? "判断相等":"判断不相等") << endl;

	

	system("pause");
	return 0;
}

案例2 点与圆的关系

#include<iostream>
using namespace std;

class Point
{
public:
	void setX(int X)
	{
		m_X = X;
	}
	int getX()
	{
		return m_X;
	}
	void setY(int Y)
	{
		m_Y = Y;
	}
	int getY()
	{
		return m_Y;
	}
private:
	int m_X;
	int m_Y;
};

class Circle
{
public:
	void setR(int R)
	{
		m_R = R;
	}
	int getR()
	{
		return m_R;
	}
	void setCenter(Point center)
	{
		m_Center= center;
	}
	Point  getCenter()
	{
		return m_Center;
	}
	

private:
	int m_R;
	Point m_Center;
};
void isInCircle(Circle c, Point p)
{
	int distance =
		(c.getCenter().getX() - p.getX()) * (c.getCenter().getX() - p.getX()) +
		(c.getCenter().getY() - p.getY()) * (c.getCenter().getY() - p.getY());
	int rDistance = c.getR() * c.getR();

	if (distance == rDistance)
	{
		cout << "点在圆上" << endl;
	}
	else if (distance > rDistance)
	{
		cout << "点在圆外" << endl;
	}
	else if (distance < rDistance)
	{
		cout << "点在圆内" << endl;
	}
}

int main() {

	Circle c;
	Point p;
	p.setX (0);
	p.setY(0);
	c.setCenter(p);
	c.setR(10);

	Point p1;
	p1.setX(2);
	p1.setY(9);

	isInCircle(c, p1);
	

	system("pause");
	return 0;
}

对象的初始化和清理

构造函数和析构函数
  • 构造函数:主要作用在于创建对象时为对象的成员属性赋值,构造函数由编译器自动调用,无须手动调用。

  • 析构函数:主要作用在于对象销毁前系统自动调用,执行一些清理工作。

#include<iostream>
using namespace std;

class Person
{
public:
	Person()
	{
		cout << "无参构造函数调用了" << endl;
	}
	Person(int a)
	{
		age = a;
		cout << "有参构造函数调用了" << endl;
	}
	Person(const Person& p) {
		age = p.age;
		cout << "拷贝构造函数!" << endl;
	}
	~Person()
	{
		cout << "析构函数调用了" << endl;
	}
public :
	int age;
};

int main() {

	//括号法
	Person p;
	Person p1(29);
	Person p3(p1);
	cout << p.age << endl;
	cout << p3.age << endl;
	cout << p1.age << endl;
	//注意1:调用无参构造函数不能加括号,如果加了编译器认为这是一个函数声明
	//Person p25();
	//void func();
	// 显式法
	
	cout << "-----------------" << endl;
	Person p2 = Person(10);
	Person p21 = Person(p1);

	//隐式转换法
	Person p4 = 10;
	Person p5 = p4;

	//匿名对象
	Person(10);
	cout << "=================" << endl;
	//注意2:不能利用 拷贝构造函数 初始化匿名对象 
	// 编译器认为是对象声明
	//Person(p4);
	
	system("pause");
	return 0;
}

拷贝构造函数调用时机

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

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

class Person
{
public:
	Person()
	{
		cout << "无参构造函数调用了" << endl;
	}
	Person(int a)
	{
		age = a;
		cout << "有参构造函数调用了" << endl;
	}
	Person(const Person& p) {
		age = p.age;
		cout << "拷贝构造函数!" << endl;
	}
	~Person()
	{
		cout << "析构函数调用了" << endl;
	}
public:
	int age;
};

void test()
{
	Person p(22);
	Person p1(p);
}
void work(Person p) {
	cout << "Person &p 拷贝构造不调用" << endl;
}

void test1()
{
	Person p2(22);
	work(p2);
}

Person work1() {
	Person p3(24);
	return p3;
}
void test2()
{
	Person p4 = work1();
}
//拷贝构造不调用   加入&& 就行
//Person& work1() {
//	Person p3(24);
//	return p3;
//}
//void test2()
//{
//	Person& p4 = work1();
//}


int main()
{
	test();
	test1();
	test2();


	system("pause");
	return 0;
}
构造函数调用规则

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

1.默认构造函数(无参,函数体为空)

2.默认析构函数(无参,函数体为空)

3.默认拷贝构造函数,对属性进行值拷贝

构造函数调用规则如下:

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

  • 如果用户定义拷贝构造函数,c++不会再提供其他构造函数

class Person {
public:
	//无参(默认)构造函数
	Person() {
		cout << "无参构造函数!" << endl;
	}
	//有参构造函数
	Person(int a) {
		age = a;
		cout << "有参构造函数!" << endl;
	}
	//拷贝构造函数
	Person(const Person& p) {
		age = p.age;
		cout << "拷贝构造函数!" << endl;
	}
	//析构函数
	~Person() {
		cout << "析构函数!" << endl;
	}
public:
	int age;
};

void test01()
{
	Person p1(18);
	//如果不写拷贝构造,编译器会自动添加拷贝构造,并且做浅拷贝操作
	Person p2(p1);

	cout << "p2的年龄为: " << p2.age << endl;
}

void test02()
{
	//如果用户提供有参构造,编译器不会提供默认构造,会提供拷贝构造
	Person p1; //此时如果用户自己没有提供默认构造,会出错
	Person p2(10); //用户提供的有参
	Person p3(p2); //此时如果用户没有提供拷贝构造,编译器会提供

	//如果用户提供拷贝构造,编译器不会提供其他构造函数
	Person p4; //此时如果用户自己没有提供默认构造,会出错
	Person p5(10); //此时如果用户自己没有提供有参,会出错
	Person p6(p5); //用户自己提供拷贝构造
}

int main() {

	test01();

	system("pause");

	return 0;
}
深拷贝与浅拷贝

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

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

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

class Person {
public:
	//无参(默认)构造函数
	Person() {
		cout << "无参构造函数!" << endl;
	}
	//有参构造函数
	Person(int age ,int height) {
		
		cout << "有参构造函数!" << endl;

		m_age = age;
		m_height = new int(height);
		
	}
	//拷贝构造函数  
	Person(const Person& p) {
		cout << "拷贝构造函数!" << endl;
		//如果不利用深拷贝在堆区创建新内存,会导致浅拷贝带来的重复释放堆区问题
		m_age = p.m_age;
		m_height = new int(*p.m_height);
		
	}

	//析构函数
	~Person() {
		cout << "析构函数!" << endl;
		if (m_height != NULL)
		{
			delete m_height;
		}
	}
public:
	int m_age;
	int* m_height;
};

void test01()
{
	Person p1(18, 180);

	Person p2(p1);

	cout << "p1的年龄: " << p1.m_age << " 身高: " << *p1.m_height << endl;

	cout << "p2的年龄: " << p2.m_age << " 身高: " << *p2.m_height << endl;
}

int main() {

	test01();

	system("pause");

	return 0;
}

总结:如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题

初始化列表

作用:

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

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

类对象作为类成员

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

例如:

class A {}
class B
{
    A a;
}

构造函数先构造A ,后构造B

析构函数先B,后A。

静态成员

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

静态成员分为:

  • 静态成员变量
    • 所有对象共享同一份数据
    • 在编译阶段分配内存
    • 类内声明,类外初始化
  • 静态成员函数
    • 所有对象共享同一个函数
    • 静态成员函数只能访问静态成员变量
#include <iostream>
using namespace std;

class Person {
public:
	static int m_A;

private :
	static int m_B;
};

int Person::m_A = 0;   //类内声明,类外初始化

int main()
{

	Person p;
	cout << p.m_A << endl;   //  0
	//cout<<p.m_B;  //不能访问
	Person p1;
	
	p.m_A = 100;
	cout << p1.m_A << endl;   //100   --- p  p1  共享m_A 
	cout << Person::m_A;  //两种访问方式  通过类名访问

	return 0;
}
class Person
{

public:

	//静态成员函数特点:
	//1 程序共享一个函数
	//2 静态成员函数只能访问静态成员变量
	
	static void func()
	{
		cout << "func调用" << endl;
		m_A = 100;
		//m_B = 100; //错误,不可以访问非静态成员变量
	}

	static int m_A; //静态成员变量
	int m_B; // 
private:

	//静态成员函数也是有访问权限的
	static void func2()
	{
		cout << "func2调用" << endl;
	}
};
int Person::m_A = 10;


void test01()
{
	//静态成员变量两种访问方式

	//1、通过对象
	Person p1;
	p1.func();

	//2、通过类名
	Person::func();


	//Person::func2(); //私有权限访问不到
}

int main() {

	test01();

	system("pause");

	return 0;
}

C++对象模型和this指针

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

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

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

class Person {

	int m_A;  //占用4
	void func() {};  //不占用
	static int m_B;  //不占用

};

int main()
{
	cout << sizeof(Person) << endl;

	return 0;

}
this指针概念

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

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

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

this指针的用途:

  • 当形参和成员变量同名时,可用this指针来区分
  • 在类的非静态成员函数中返回对象本身,可使用return *this
#include <iostream>
using namespace std;

class Person {
public:

	Person(int age) {
		this->age = age;
	}

	Person& PersonAddAge(int age) {
		this->age += age;
		return *this;
	}

	int age;

};


void test6()
{
	Person p(32);
	cout << p.age << endl;
	Person p2(p);
	cout << p2.age << endl;
	p2.PersonAddAge(1).PersonAddAge(1).PersonAddAge(1);
	cout << p2.age << endl;

}

int main() {

	test6();

	system("pause");

	return 0;
}
Person& PersonAddAge(int age) {
		this->age += age;
		return *this;   
	}   

this 是指针,*this是对象,&是引用,如果没有&,age不会累加。一直返回p2。

空指针访问成员函数

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

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

#include <iostream>
using namespace std;

class Person {
public:

	void showAge() {
		if (this == NULL) {
			return;
		}
		cout << age << endl;
	}

	void hello() {
		cout << "Hello!" << endl;
	}

	int age;

};


void test6()
{
	Person *p = NULL;
	//p->showAge();
	p->hello();

}

int main() {

	test6();

	system("pause");

	return 0;
}
const修饰成员函数

常函数:

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

常对象:

  • 声明对象前加const称该对象为常对象
  • 常对象只能调用常函数
#include <iostream>
using namespace std;

class Person {
public:

	void showAge() const{
		if (this == NULL) {
			return;
		}
		cout << age << endl;
	}

	void hello() const{
		this->id = 33;
		cout << "Hello!" << endl;
		cout << this->id<< endl;
	}

	int age;
	mutable int id;

};


void test6()
{
	Person p;
	//p->showAge();
	p.hello();

}

int main() {

	test6();

	system("pause");

	return 0;
}

友元

友元的三种实现

  • 全局函数做友元

  • 类做友元

  • 成员函数做友元

    全局函数做友元
#include <iostream>
using namespace std;

class Building {
	friend void godGay(Building building);

public:
	Building() {
		settingroom = "客厅";
		bedroom = "卧室";
	}

public:
	
	string settingroom;

private:
	string bedroom;
};

void godGay(Building building) {
	cout << "好基友在访问" << building.settingroom << endl;
	cout << "好基友在访问" << building.bedroom << endl;
}


int main()
{

	Building b;
	godGay(b);

	cout << "Hello World";
	return 0;
}
类做友元
#include <iostream>
using namespace std;

//class Building;



class Building {
	
	friend class goodGay;
public:
	Building() {
	settingroom = "客厅";
		bedroom = "卧室";
		}

public:

	string settingroom;

private:
	string bedroom;
};

class goodGay {
public:
	goodGay();
	void visit();
private:
	Building building;
};

goodGay::goodGay() {
	//building = new Building;
}
void goodGay::visit() {
	cout << "好基友正在访问" << building.settingroom << endl;
	cout << "好基友正在访问" << building.bedroom << endl;
}



int main()
{

	goodGay gg;
	gg.visit();

	cout << "Hello World";
	return 0;
}
成员函数做友元
#include <iostream>
using namespace std;

class Building;

//class goodGay;


class goodGay {
public:
	goodGay();
	void visit1();

private:
	Building* building;
};


class Building {
	
	friend void goodGay::visit1();
public:
	Building() {
	settingroom = "客厅";
		bedroom = "卧室";
		}

public:

	string settingroom;

private:
	string bedroom;
};



goodGay::goodGay() {
	
	building = new Building;
}
void goodGay::visit1() {
	cout << "好基友正在访问" << building->settingroom << endl;
	cout << "好基友正在访问" << building->bedroom << endl;
}




int main()
{

	goodGay gg;
	gg.visit1();

	cout << "Hello World";
	return 0;
}

运算符重载

运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型

加号运算符重载

作用:实现两个自定义数据类型相加的运算

class Person {
public:
	Person() {};
	Person(int a, int b)
	{
		this->m_A = a;
		this->m_B = b;
	}
	//成员函数实现 + 号运算符重载
	Person operator+(const Person& p) {
		Person temp;
		temp.m_A = this->m_A + p.m_A;
		temp.m_B = this->m_B + p.m_B;
		return temp;
	}


public:
	int m_A;
	int m_B;
};

//全局函数实现 + 号运算符重载
//Person operator+(const Person& p1, const Person& p2) {
//	Person temp(0, 0);
//	temp.m_A = p1.m_A + p2.m_A;
//	temp.m_B = p1.m_B + p2.m_B;
//	return temp;
//}

//运算符重载 可以发生函数重载 
Person operator+(const Person& p2, int val)  
{
	Person temp;
	temp.m_A = p2.m_A + val;
	temp.m_B = p2.m_B + val;
	return temp;
}

void test() {

	Person p1(10, 10);
	Person p2(20, 20);

	//成员函数方式
	Person p3 = p2 + p1;  //相当于 p2.operaor+(p1)
	cout << "mA:" << p3.m_A << " mB:" << p3.m_B << endl;


	Person p4 = p3 + 10; //相当于 operator+(p3,10)
	cout << "mA:" << p4.m_A << " mB:" << p4.m_B << endl;

}

int main() {

	test();

	system("pause");

	return 0;
}

总结1:对于内置的数据类型的表达式的的运算符是不可能改变的

总结2:不要滥用运算符重载

左移运算符重载

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

class Person {
	friend ostream& operator<<(ostream& out, Person& p);

public:

	Person(int a, int b)
	{
		this->m_A = a;
		this->m_B = b;
	}

	//成员函数 实现不了  p << cout 不是我们想要的效果
	//void operator<<(Person& p){
	//}

private:
	int m_A;
	int m_B;
};

//全局函数实现左移重载
//ostream对象只能有一个
ostream& operator<<(ostream& out, Person& p) {
	out << "a:" << p.m_A << " b:" << p.m_B;
	return out;
}

void test() {

	Person p1(10, 20);

	cout << p1 << "hello world" << endl; //链式编程
}

int main() {

	test();

	system("pause");

	return 0;
}

总结:重载左移运算符配合友元可以实现输出自定义数据类型

递增运算符重载

作用: 通过重载递增运算符,实现自己的整型数据

#include <iostream>
using namespace std;

class myInteger {
	friend ostream& operator<<(ostream& cout, myInteger myInt);

public:
	myInteger() {
		m_Num = 0;
	}
	myInteger operator++() {
		m_Num++;
		return *this;
	}
	myInteger operator++(int) {
		myInteger temp = *this;
		m_Num++;
		return temp;
	}


private :
	int m_Num = 0;
};
ostream& operator<<(ostream &cout, myInteger myInt) {
	cout << myInt.m_Num << endl;
	return cout;
}

int main()
{
	myInteger myInt;
	cout << myInt++ << endl;
	cout << myInt << endl;

	cout << "=====================" << endl;
	cout << myInt.operator++(5) << endl;
	cout << myInt << endl;
	cout << "=====================" << endl;

	myInteger myInt2;
	cout << ++myInt2 << endl;
	cout << myInt2<< endl;
	cout << "=====================" << endl;
	cout << myInt2.operator++() << endl;
	cout << myInt2 << endl;


	cout << "Hello World";
	return 0;
}
赋值运算符重载

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

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

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

#include <iostream>
using namespace std;

class Person {

public:
	Person(int age) {
		this->age = new int(age);
		cout << *this->age << endl;
	}

	Person &operator=(Person & p) {
		this->age = p.age;
		this->age = new int(*p.age);
		return *this;
	}

	~Person() {
		if (age != NULL) {
			delete age;
			age = NULL;	
		}
	}

	int* age;

};

int main()
{
	Person p(12);
	Person p2(23);
	p = p2;
	cout << *p.age << endl;

	Person p3(32);
	p = p2 = p3;
	cout << *p.age << endl;
	cout << *p2.age << endl;
	cout << *p3.age << endl;


	cout << "Hello World";
	return 0;
}
关系运算符重载

**作用:**重载关系运算符,可以让两个自定义类型对象进行对比操作

#include <iostream>
using namespace std;

class Person {

public:
	Person(string name,int age) {
		this->age = age;
		this->name = name;
	}
	bool operator==(Person p1) {
		if (p1.name == this->name && p1.age == this->age) {
			return 1;
		}
		else {
			return 0;
		}
	}
	bool operator!=(Person p1) {
		if (p1.name == this->name && p1.age == this->age) {
			return 0;
		}
		else {
			return 1;
		}
	}

	int age;
	string name;

};


int main()
{
	Person p1("tom", 23);
	Person p2("tom", 3);

	if (p1 == p2) {
		cout << "他们是相等的" << endl;
	}
	else {
		cout << "他们是不相等的" << endl;
	}
	if (p1 != p2) {
		cout << "他们是不相等的" << endl;
	}
	else {
		cout << "他们是相等的" << endl;
	}



	cout << "Hello World";
	return 0;
}
函数调用运算符重载
  • 函数调用运算符 () 也可以重载
  • 由于重载后使用的方式非常像函数的调用,因此称为仿函数
  • 仿函数没有固定写法,非常灵活
#include <iostream>
using namespace std;

class MyPrint {
public:
	void operator()(string test) {
		cout << test << endl;
	}
};

int MyAdd(int a, int b) {
	return a + b;
}

int main()
{
	MyPrint myPrint;
	myPrint("()重载");

	cout << MyAdd(13,34)<< endl;


	cout << "Hello World";
	return 0;
}

继承

继承是面向对象三大特性之一

继承的好处:可以减少重复的代码

class A : public B{}

A 类称为子类 或 派生类

B 类称为父类 或 基类

派生类中的成员,包含两大部分

一类是从基类继承过来的,一类是自己增加的成员。

从基类继承过过来的表现其共性,而新增的成员体现了其个性。

继承方式

继承的语法:class 子类 : 继承方式 父类

继承方式一共有三种:

  • 公共继承
  • 保护继承
  • 私有继承

在这里插入图片描述

继承中的对象模型

利用工具查看:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-STdThx87-1670596173651)(C:\Users\chan\Desktop\day_note.assets\1545881904150.png)]

打开工具窗口后,定位到当前CPP文件的盘符

然后输入: cl /d1 reportSingleClassLayout查看的类名 所属文件名

结论: 父类中私有成员也是被子类继承下去了,只是由编译器给隐藏后访问不到

继承中构造和析构顺序

子类继承父类后,当创建子类对象,也会调用父类的构造函数

class Base 
{
public:
	Base()
	{
		cout << "Base构造函数!" << endl;
	}
	~Base()
	{
		cout << "Base析构函数!" << endl;
	}
};

class Son : public Base
{
public:
	Son()
	{
		cout << "Son构造函数!" << endl;
	}
	~Son()
	{
		cout << "Son析构函数!" << endl;
	}

};

继承中 先调用父类构造函数,再调用子类构造函数,析构顺序与构造相反

继承同名成员处理方式
  • 访问子类同名成员 直接访问即可
  • 访问父类同名成员 需要加作用域
	Son s;

	cout << "Son下的m_A = " << s.m_A << endl;
	cout << "Base下的m_A = " << s.Base::m_A << endl;

	s.func();
	s.Base::func();
	s.Base::func(10);

总结:

  1. 子类对象可以直接访问到子类中同名成员
  2. 子类对象加作用域可以访问到父类同名成员
  3. 当子类与父类拥有同名的成员函数,子类会隐藏父类中同名成员函数,加作用域可以访问到父类中同名函数
继承同名静态成员处理方式

问题:继承中同名的静态成员在子类对象上如何进行访问?

静态成员和非静态成员出现同名,处理方式一致

  • 访问子类同名成员 直接访问即可
  • 访问父类同名成员 需要加作用域
//同名成员属性
void test01()
{
	//通过对象访问
	cout << "通过对象访问: " << endl;
	Son s;
	cout << "Son  下 m_A = " << s.m_A << endl;
	cout << "Base 下 m_A = " << s.Base::m_A << endl;

	//通过类名访问
	cout << "通过类名访问: " << endl;
	cout << "Son  下 m_A = " << Son::m_A << endl;
	cout << "Base 下 m_A = " << Son::Base::m_A << endl;
}

//同名成员函数
void test02()
{
	//通过对象访问
	cout << "通过对象访问: " << endl;
	Son s;
	s.func();
	s.Base::func();

	cout << "通过类名访问: " << endl;
	Son::func();
	Son::Base::func();
	//出现同名,子类会隐藏掉父类中所有同名成员函数,需要加作作用域访问
	Son::Base::func(100);
}
多继承语法

C++允许一个类继承多个类

语法: class 子类 :继承方式 父类1 , 继承方式 父类2...

多继承可能会引发父类中有同名成员出现,需要加作用域区分

C++实际开发中不建议用多继承

//多继承容易产生成员同名的情况
//通过使用类名作用域可以区分调用哪一个基类的成员
void test01()
{
	Son s;
	cout << "sizeof Son = " << sizeof(s) << endl;
	cout << s.Base1::m_A << endl;
	cout << s.Base2::m_A << endl;
}

总结: 多继承中如果父类中出现了同名情况,子类使用时候要加作用域

菱形继承

菱形继承概念:

​ 两个派生类继承同一个基类

​ 又有某个类同时继承者两个派生类

​ 这种继承被称为菱形继承,或者钻石继承

class Animal
{
public:
	int m_Age;
};

//继承前加virtual关键字后,变为虚继承
//此时公共的父类Animal称为虚基类
class Sheep : virtual public Animal {};
class Tuo   : virtual public Animal {};
class SheepTuo : public Sheep, public Tuo {};


void test01()
{
	SheepTuo st;
	st.Sheep::m_Age = 100;
	st.Tuo::m_Age = 200;

	cout << "st.Sheep::m_Age = " << st.Sheep::m_Age << endl;
	cout << "st.Tuo::m_Age = " <<  st.Tuo::m_Age << endl;
	cout << "st.m_Age = " << st.m_Age << endl;
}

总结:

  • 菱形继承带来的主要问题是子类继承两份相同的数据,导致资源浪费以及毫无意义
  • 利用虚继承可以解决菱形继承问题

多态

多态的基本概念

多态是C++面向对象三大特性之一

多态分为两类

  • 静态多态: 函数重载 和 运算符重载属于静态多态,复用函数名
  • 动态多态: 派生类和虚函数实现运行时多态

静态多态和动态多态区别:

  • 静态多态的函数地址早绑定 - 编译阶段确定函数地址
  • 动态多态的函数地址晚绑定 - 运行阶段确定函数地址
#include <iostream>
using namespace std;

class Animal {

public :
	virtual void speak() {
		cout << "动物在说话" << endl;
	}
};
class Cat : public Animal {

public :
	void speak() {
		cout << "猫在说话" << endl;
	}
};
void animalSpeak(Animal &animal) { //不加& ,加了virtual 也是动物在说话。
	animal.speak();
}


int main()
{
	Cat cat;
	animalSpeak(cat);


	system("pause");
	return 0;
}

总结:

父类 加virtual

方法加&

多态案例-计算器
#include <iostream>
using namespace std;

class Calculator {

public:
	int getResult(string oper)
	{
		if (oper == "-") {
			return m_Num1 - m_Num2;
		}
		if (oper == "+") {
			return m_Num1+ m_Num2;
		}
		if (oper == "*") {
			return m_Num1 *m_Num2;
		}
	}

	int m_Num1;
	int m_Num2;
};

class AbstractCalculator
{
public :
	virtual int getResult()
	{
		return 0;
	}

	int m_Num1;
	int m_Num2;
};
class AddCalculator : public AbstractCalculator
{
public :
	int getResult()
	{
		return m_Num1 +m_Num2;
	}
};
class SubCalculator : public AbstractCalculator
{
public :
	 int getResult()
	{
		return m_Num1 - m_Num2;
	}
};
class MulCalculator : public AbstractCalculator
{
public :
	 int getResult()
	{
		return m_Num1 * m_Num2;
	}
};

void test()
{

	AbstractCalculator* abc = new AddCalculator;
	abc->m_Num1 = 100;
	abc->m_Num2 = 100;
	cout << abc->m_Num1 << "+" << abc->m_Num2 << "=" << abc->getResult() << "   地址"<<abc << endl;
	delete abc;

	abc = new SubCalculator;
	abc->m_Num1 = 100;
	abc->m_Num2 = 100;
	cout << abc->m_Num1 << "-" << abc->m_Num2 << "=" << abc->getResult() << "   地址" << abc<<endl;
	delete abc;

	abc = new MulCalculator;
	abc->m_Num1 = 100;
	abc->m_Num2 = 100;
	cout << abc->m_Num1 << "*" << abc->m_Num2 << "=" << abc->getResult() << "   地址" << abc<<endl;
	delete abc;
}


int main()
{
	Calculator c;
	c.m_Num1 = 22;
	c.m_Num2 = 34;
	cout << c.m_Num1 << "+" << c.m_Num2 << "=" << c.getResult("+") << endl;

	test();

	system("pause");
	return 0;
}
纯虚函数和抽象类

在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容

因此可以将虚函数改为纯虚函数

纯虚函数语法:virtual 返回值类型 函数名 (参数列表)= 0 ;

当类中有了纯虚函数,这个类也称为抽象类

抽象类特点

  • 无法实例化对象
  • 子类必须重写抽象类中的纯虚函数,否则也属于抽象类
#include <iostream>
using namespace std;

class Animal {

public:
	virtual void speak() = 0;
};
class Cat : public Animal {

public:
	void speak() {
		cout << "猫在说话" << endl;
	}
};
void animalSpeak(Animal& animal) { //不加& ,加了virtual 也是动物在说话。
	animal.speak();
}


int main()
{
	Cat cat;
	animalSpeak(cat);


	system("pause");
	return 0;
}
多态案例二: 制作饮品
#include <iostream>
using namespace std;

class yinpin {
public:
	virtual void zhushui() = 0;
	virtual void chongshui() = 0;
	virtual void wait() = 0;

	void zhizuo() {
		zhushui();
		chongshui();
		wait();
	}

};

class kaffe :public yinpin{
	virtual void zhushui() {
		cout << "煮水" << endl;
	};
	virtual void chongshui() {
		cout << "放入咖啡粉" << endl;
	};
	virtual void wait() {
		cout << "等待10分钟" << endl;
	};

};
class tea :public yinpin{
	virtual void zhushui() {
		cout << "煮水" << endl;
	};
	virtual void chongshui() {
		cout << "放入茶叶" << endl;
	};
	virtual void wait() {
		cout << "等待10分钟" << endl;
	};

};

void Make(yinpin &y) {
	y.zhizuo();
}
void Make(yinpin *y) {
	y->zhizuo();
}

int main() {

	kaffe k;
	tea t;

	Make(k);
	cout << "================" << endl;
	Make(t);

	cout << "================" << endl;

	Make(new kaffe);
	cout << "================" << endl;
	Make(new tea);


	system("pause");
	return 0;
}
虚析构和纯虚析构

多态使用时,如果子类中有属性开辟到堆区,那么父类指针在释放时无法调用到子类的析构代码

解决方式:将父类中的析构函数改为虚析构或者纯虚析构

虚析构和纯虚析构共性:

  • 可以解决父类指针释放子类对象
  • 都需要有具体的函数实现

虚析构和纯虚析构区别:

  • 如果是纯虚析构,该类属于抽象类,无法实例化对象

虚析构语法:

virtual ~类名(){}

纯虚析构语法:

virtual ~类名() = 0;

类名::~类名(){}

#include <iostream>
using namespace std;

class Animal {
	
public:
	Animal() {
		cout << "Animal构造函数" << endl;
	}
	virtual void speak() = 0;

	virtual~Animal() {
		cout << "Animal虚构函数" << endl;
	}
};
class Cat : public Animal {

public:
	Cat(string name) {
		cout << "Cat构造函数" << endl;
		this->name = new string(name);
	}

	void speak() {
		cout <<*name<< "猫在说话" << endl;
	}
	~Cat() {
		cout << "猫析构函数" << endl;
		if (name != NULL) {
			delete name;
			name = NULL;
		}
	}

	string* name;
};

void test() {
	Animal* animal = new Cat("Tom");
	animal->speak();//指针多态调用会直接调用基类析构,写virtual可以调用子类析构
	delete animal;
}



int main()
{
	test();
	cout << "===========" << endl;
	Cat cat("Tom");// 普通函数调用不会出现问题
	cat.speak();


	system("pause");
	return 0;
}

//指针多态调用会直接调用基类析构,写virtual可以调用子类析构

多态:电脑组装
#include <iostream>
using namespace std;

class CPU
{
public:
	virtual void work() = 0;
};
class GPU
{
public:
	virtual void work() = 0;
};
class CPUInter: public CPU
{
public:
	virtual void work() {
		cout << "英特尔的CPU开始工作了" << endl;
	}
};
class CPUApple : public CPU
{
public:
	virtual void work() {
		cout << "苹果的CPU开始工作了" << endl;
	}
};

class GPUInter: public GPU
{
public:
	virtual void work() {
		cout << "英特尔的GPU开始工作了" << endl;
	}
};
class GPUApple : public GPU
{
public:
	virtual void work() {
		cout << "苹果的GPU开始工作了" << endl;
	}
};
class Computer
{
public:
	Computer(GPU *gpu, CPU* cpu)
	{
		this->gpu = gpu;
		this->cpu = cpu;
	}
	void work() {
		cout << "电脑工作了" << endl;
		gpu->work();
		cpu->work();
		
	}
	~Computer() {
		if (gpu != NULL) {
			delete gpu;
			gpu = NULL;
		}
		if (cpu != NULL) {
			delete cpu;
			cpu = NULL;
		}
	}

private:
	GPU *gpu;
	CPU *cpu;
};

int main() {

	Computer c(new GPUInter, new CPUInter);
	c.work();
	Computer c1(new GPUApple, new CPUApple);
	c1.work();



	system("pause");
	return 0;
}

文件操作

文本文件

写文件

写文件步骤如下:

  1. 包含头文件

    #include <fstream>

  2. 创建流对象

    ofstream ofs;

  3. 打开文件

    ofs.open(“文件路径”,打开方式);

  4. 写数据

    ofs << “写入的数据”;

  5. 关闭文件

    ofs.close();

文件打开方式:

打开方式解释
ios::in为读文件而打开文件
ios::out为写文件而打开文件
ios::ate初始位置:文件尾
ios::app追加方式写文件
ios::trunc如果文件存在先删除,再创建
ios::binary二进制方式

注意: 文件打开方式可以配合使用,利用|操作符

**例如:**用二进制方式写文件 ios::binary | ios:: out

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


int main() {

	ofstream out;

	out.open("test.txt", ios::out);

	out << "张三" << endl;
	out << "男" << endl;
	out << "19" << endl;

	out.close();


	system("pause");
	return 0;
}

总结:

  • 文件操作必须包含头文件 fstream
  • 读文件可以利用 ofstream ,或者fstream类
  • 打开文件时候需要指定操作文件的路径,以及打开方式
  • 利用<<可以向文件中写数据
  • 操作完毕,要关闭文件
读文件

读文件与写文件步骤相似,但是读取方式相对于比较多

读文件步骤如下:

  1. 包含头文件

    #include <fstream>

  2. 创建流对象

    ifstream ifs;

  3. 打开文件并判断文件是否打开成功

    ifs.open(“文件路径”,打开方式);

  4. 读数据

    四种方式读取

  5. 关闭文件

    ifs.close();

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

void test1() {
	ofstream out;

	out.open("test.txt", ios::out);

	out << "张三" << endl;
	out << "男" << endl;
	out << "19" << endl;

	out.close();
}

void test2() {
	ifstream ifs;
	
	ifs.open("test.txt", ios::in);

	//四种读写方式,每一种都可以读出,但是四种合起来用自会读出一份数据
	//一种方法用两次也一样只会读出一份数据,是指针的问题,要想读多点必须要把指针指向文件头

	if (!ifs.is_open())
	{
		cout << "打开失败" << endl;
		return;
	}

	/*char a[1024] = { 0 };
	while (ifs >> a) {
		cout << a<< endl;
	}*/

	//char b[1024] = { 0 };
	//while (ifs.getline(b, sizeof(b))) {
	//	cout << b << endl;
	//}

	//string c;
	//while(getline(ifs,c) )
	//{
	//	cout << c << endl;
	//}

	char d;
	while((d=ifs.get()) != EOF) {
		cout << d ;  //  加了<< endl  将会读不出汉字,数字换行读出 
	}
	char e;
	while((e=ifs.get()) != EOF) {
		cout << e ;  //  加了<< endl  将会读不出汉字,数字换行读出 
	}

	ifs.close();
}


int main() {

	
	test2();

	system("pause");
	return 0;
}

二进制文件

以二进制的方式对文件进行读写操作

打开方式要指定为 ios::binary

写文件

二进制方式写文件主要利用流对象调用成员函数write

函数原型 :ostream& write(const char * buffer,int len);

参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

总结:

  • 文件输出流对象 可以通过write函数,以二进制方式写数据
读文件

二进制方式读文件主要利用流对象调用成员函数read

函数原型:istream& read(char *buffer,int len);

参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

文件输入流对象 可以通过read函数,以二进制方式读数据

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

class Person
{
public:
	
	char name[64];
	int age;
};

void test1() {
	ofstream ofs;

	ofs.open("Personw.txt", ios::out | ios::binary);

	Person p = { "张三", 18 };

	ofs.write((const char*)&p, sizeof(p));

	ofs.close();

}

void test2() {

	ifstream ifs;

	ifs.open("Personw.txt", ios::in | ios::binary);

	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
	}

	Person p1;

	ifs.read((char*)&p1, sizeof(p1));

	cout << "姓名: " << p1.name << "  年龄: " << p1.age << endl;

	ifs.close();

}

int main() {

	test1();

	test2();

	system("pause");
	return 0;
}

**注:**name 必须用char, 否则报bug

class Person
{
public:
	

	char name[64];
	int age;

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值