admin管理员组文章数量:1598839
cpp课堂笔记(黑马程序员)
- class1字符和数据
- 效果![在这里插入图片描述](https://i-blog.csdnimg/blog_migrate/3e4d03931f4122052078d7330469313d.png)
- class2运算符
- class3选择结构
- if
- if例题,三小猪称体重
- switch
- 三目运算符
- class4循环结构
- while
- while例题-猜数字
- do while
- do while例题—水仙花数
- for
- class5嵌套循环
- 星阵
- 九九乘法表
- 效果![在这里插入图片描述](https://i-blog.csdnimg/blog_migrate/b7acc19f5654363a6e2a57ea82b3f5c7.png#pic_center)
- 递归
- 阶乘
- 逆输出
- 汉诺塔
- class6跳转语句
- break
- continue
- goto
- class7一维数组
- 数组名和定义
- 案例一 五只小猪称体重
- 案例二 元素逆置
- 重点学习对换数值三步法
- 冒泡排序
- 效果
- 二维数组
- 二维数组的定义方式&名称的用途
- 应用案例——考试成绩统计
- class8函数
- 声名&类型
- 各种常用函数的定义
- 函数的分文件编写
- add.h
- add.cpp
- 源.cpp
- class9指针
- 基础知识
- const常量指针&指针常量
- 指针和数组
- 内存
- new运算符
- delete运算符
- class10结构体
- 定义和创建
- 结构体数组
- 结构体指针
- 结构体嵌套结构体
- 结构体做参数函数
- 结构体中使用const
- 案例-嵌套结构体输出
- 效果
- 案例-结构体数组排序
- 效果
- 核心知识
- 内存分区模型
- 引用
- 1. 做函数参数
- 2. 做函数的返回值
- 3.引用本质
- 4.常量引用
- 5.在函数形参列表中,可以加const修饰形参,防止形参改变实参
- 函数提高
- 函数重载
- 内联函数
- class11类和对象
- 设计一个类
- 效果
- 访问权限—成员属性设置为私有
- 设计立方体类
- 设计点和圆的关系类
- 分文件编写
- point.h
- point.cpp
- circle.h
- circle.cpp
- cpp
- 构造函数和析构函数(对象的初始化清理)
- 函数的分类和调用
- 拷贝构造函数的调用时机
- 构造函数的调用规则
- 深拷贝与浅拷贝
- 初始化列表
- 类对象作为类成员
- 静态成员
- C++对象模型和this指针
- **成员变量和成员函数分开存储**
- this指针
- 空指针返回成员函数
- const修饰成员函数
- 友元
- 全局函数做友元friend void goodgay(Building* building);
- 类做友元friend class GoodGay;
- 成员函数做友元friend void GoodGay::visit();
- 运算符重载
- **加号运算符重载**Person operator+(Person& p) 、Person operator+(Person& p1, Person& p2)
- **左移运算符重载**ostream& operator<<(ostream &cout, Person &p)
- **递增运算符重载**MyInteger& operator++()
- **赋值运算符重载**Person& operator=(Person &p)
- 关系运算符重载bool operator==(Person &p)
- 函数调用运算符重载int operator()(int a, int b)
- 继承
- 什么不可以被继承?
- eg1
- 继承方式(有图)
- 继承中的对象模型&利用VS的开发人员命令提示工具查看对象模型
- 继承中构造和析构的顺序
- 继承同名成员处理方式
- 继承同名静态成员处理方式
- 多继承语法
- 菱形继承(虚继承)
- 文件操作
- 文本文件写文件
- 文本文件读文件
- 二进制文件写文件
- 二进制方式读文件
class1字符和数据
2. 字符串常量
字符串常量又称字符串,是由一对双引号括起来的字符序列。
字符常量和字符串常量都是不同的。这不仅是表示形式上的不同,而且在存储方式上也不同。在C++中,字符串常量总是以 ‘\0’ 结束。如果有一个字符串“PROGRAM”,那它在内存中的表示为连续8个内存单元,如下图所示。
不能将字符串常量赋值给字符变量。一个字符占有一个内存单元,含有一个字符的字符串占有2个内存单元,第2个内存单元存放‘\0’结束符。
#include<iostream>
using namespace std;
//定义宏常量,数据不可修改
#define Day 7
int main()
{ //数据类型
//const修饰的变量也是不可更改的常量
const int month = 12;
cout << "hello world" << endl;//输出语言
int a = 10;
cout << "a=" << a<<endl;
cout << "一年有:" << month << "个月份"<<endl;
cout << "一周天数:" << Day<<endl;
short num = 1;
cout << sizeof(short)<<endl;//显示不同数据类型内存空间
float num1 = 2.2f;//在float后面加一个f,否则默认2.2是double
cout << sizeof(float)<<endl;
float f1 = 3e2;//3*10^2 正数
float f2 = 3e-2;//3*0.1^2 负数
cout << f1 + f2<<endl;
double num2 = 10.1111111;
cout << sizeof(double)<<endl;
cout << num2<<endl;//输出一个小数默认是六位
/*%f 以十进制形式输出 float 类型;
%lf 以十进制形式输出 double 类型;
%e 以指数形式输出 float 类型,输出结果中的 e 小写;
%E 以指数形式输出 float 类型,输出结果中的 E 大写;
%le 以指数形式输出 double 类型,输出结果中的 e 小写;
%lE 以指数形式输出 double 类型,输出结果中的 E 大写。
%g 和 %lg 分别用来输出 float 类型和 double 类型,并且当以指数形式输出时,e小写。
%G 和 %lG 也分别用来输出 float 类型和 double 类型,只是当以指数形式输出时,E大写。
————————————————
版权声明:本文为CSDN博主「列队猫」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn/qq_43915356/article/details/108637029*/
//进制转换
int num=10;
cout <<"十六进制:"<< hex <<num<<endl;
cout <<"八进制:"<< oct <<num<<endl;//一般大家默认二进制,八进制,十进制,十六进制分别用字符:bin, oct, dec, hex 来表示
//字符型变量
char ch = 'a';//一定不可以用双引号,只能用字母
cout << sizeof(char) << endl;//占位一字节
cout << (int)ch<<endl;//强行化字符型为整型
//ASCII编码 a-97 A-65
//转义字符
cout << "hello world\n";//换行
cout << "\\" << endl;//输出\
cout << "aa\thelloworld" << endl;//\t:水平制表符
cout << "aaaa\thelloworld" << endl;
cout << "aaa\thelloworld" << endl;
//字符串
string str1 = "hello";
cout << str1 << endl;
//bool
bool flag = true;
cout << flag << endl;//1真0假
flag = false;
cout << flag << endl;
//数据的输入
//整型
int b= 0;
cout << "请给整型变量b赋值:" << endl;
cin >> b;
cout << "b="<< b<<endl;
system("pause");
return 0;
}
效果
class2运算符
#include <iostream>;
using namespace std;
int main()
{ //加减乘除
int a1 = 1;
int b1 = 2;
float c1 = 0.5f;
float c2 = .22f;
cout << a1 + b1 << endl;
cout << a1 - b1 << endl;
cout << a1 * b1 << endl;
cout << a1 / b1 << endl;//整数相除结果依然是整数,直接去除小数位
cout << c1 / c2 << endl;
//取余运算
int d1 = 10;
int d2 = 3.1;
cout << "取余:"<<d1 % d2 << endl;//不可以两个小数取余
//前置递增和后置递增
int e1 = 10;
int e2 = 10;
int f1 = ++e1 * 10;
int g1 = e2++ * 10;
cout << "前置递增:" << e1 << endl;
cout << "前置递增:" << f1 << endl;//先给e1递增加一,再参与运算
cout << "后置递增: " << e2 << endl;
cout << "后置递增:" << g1 << endl;//先用e2参与运算,在对e2加一赋值
//赋值运算符
int a = 10;
a += 2;//a=a+2
cout << a << endl;
a = 10;
a /= 2;
cout << a << endl;
//比较运算符
//==;>=;<=;(优先运算)
int k = 10;
int m = 20;
cout << (k > m) << endl;
//逻辑运算符
//非:!
int num1 = 0;
cout << "0false others true:" << !num1 << endl;
//与:&&
int num2 = 10;
int num3 = 10;
cout << (num2 && num3) << endl;//同真为真,一假全假
//逻辑或:||
int num4 = 10;
int num5 = 0;
cout << (num4 || num5) << endl;//同假为假,其余为真
system("pause");
return 0;
}
class3选择结构
if
#include <iostream>;
using namespace std;
int main()
{
int score = 0;
cout << "plz cin your score:" << endl;
cin >> score;
cout << "this is your score:" <<score<< endl;
if (score >= 600)
{
cout << "congratuations!" << endl;
if (score > 700) //嵌套if
{
cout << "beida" << endl;
}
else if (score > 650)
{
cout << "qinghua" << endl;
}
else
{
cout << "renda" << endl;
}
}
else if (500 <score)
{
cout << "keep on" << endl;
}
else
{
cout << "i am so sorry" << endl;
}
system("pause");
return 0;
}
if例题,三小猪称体重
#include <iostream>;
using namespace std;
//三只小猪称体重
int main()
{
int w1 = 0;
int w2 = 0;
int w3 = 0;
cout << "请输入第一只小猪重:" << endl;
cin >> w1;
cout << "请输入第二只小猪重:" << endl;
cin >> w2;
cout << "请输入第三只小猪重:" << endl;
cin >> w3;
if (w1 <w2)
{
if (w2 < w3)
{
cout << "最重的是3号小猪" << endl;
}
else
{
cout << "2" << endl;
}
}
else
{
if (w1 > w3)
{
cout << "1" << endl;
}
else
{
cout << "3" << endl;
}
}
system("pause");
return 0;
}
switch
#include <iostream>;
using namespace std;
int main()
{
int score = 0;
cout << "pla give your score:" << endl;
cin >> score;
cout << "your score:" << score << endl;
switch (score)//不可判断区间,仅仅整型和字符型
{
case 10:
cout << "u like it !" << endl;
break;
//退出当前分支,否则会执行所有case
case 5:
cout << "u don't like it" << endl;
default:
cout << "choose 10 or 5 plz" << endl;
break;
}
system("pause");
return 0;
}
三目运算符
表达式1?表达式2:表达式3
解释:
如果1为真,则结果为表达式2的值。
如果1为假,则结果为表达式3的值。
#include <iostream>;
using namespace std;
int main()
{
int a = 10;
int b = 20;
int c = 0;
c = (a > b ? a : b);
cout << "c=" << c << endl;
//返回变量,可继续赋值
(a > b ? a : b)=100;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
system("pause");
return 0;
}
class4循环结构
while
#include <iostream>;
using namespace std;
int main()
{
int num = 0;
while (num < 10)//不要死循环,有退出的出口
{
cout << num << endl;
num++;
}
system("pause");
return 0;
}
while例题-猜数字
#include <iostream>
using namespace std;
int main()
{
srand((unsigned int)time(NULL));//加一个随机数种子
int random_num = rand() % 100 + 1;
// rand()%100 :0~99
cout << "guess a num:" << endl;
int guess = 0;
while (1)
{
cin >> guess;
if (guess > random_num)
{
cout << "too big,once again!" << endl;
}
else if (guess < random_num)
{
cout << "too small,once again!" << endl;
}
else
{
cout << "guess right" << endl;
break;
}
}
system("pause");
return 0;
}
do while
#include <iostream>
using namespace std;
int main()
{
int num = 1;
do
{
cout << num << endl;
num++;
} while (num < 10);//先执行一次语句,再判断条件
return 0;
}
do while例题—水仙花数
#include <iostream>
using namespace std;
int main()
{
int num = 100;
do
{
int a = 0;
int b1 = 0;
int b = 0;
int c = 0;
a = num / 100;//百位
b1 = num / 10;
b = b1 % 10;//十位
c = num % 10;//个位
if ( a*a*a + b*b*b + c*c*c == num)
{
cout << num << endl;
}
num++;
} while (num < 1000);
return 0;
}
for
for循环一般应用于循环次数已知的情况,而while循环一般应用于循环次数未知的情况。
在一般情况下,这两者是可以相互转化的。
#include <iostream>
using namespace std;
int main()
{
//for循环(起始表达式(声名或赋值);条件表达式;末尾循环体(一次循环后执行)){循环语句;}
for (int i = 0; i <= 100; i++)
{
if (i % 10 == 7 || i % 7 == 0 || i/10==7)//7的倍数或者含7的数字
{
cout << "敲桌子" << endl;
}
else
{
cout << i << endl;
}
}
system("pause");
return 0;
}
class5嵌套循环
星阵
#include <iostream>
using namespace std;
int main()
{
//外层执行一次,内层循环一周
for (int i = 0; i < 10; i++)
{
for (int i = 0; i < 10; i++)//外层循环
{
for (int i1 = 0; i1 < 10; i1++)//内层循环
{
cout << "* ";
}
cout << endl;
}
cout << endl;
}
system("pause");
return 0;
}
九九乘法表
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i < 10; i++)//行数
{
//难点:行数与列数的约束关系
for (int j = 1; j <= i; j++)//列数
{
cout << " " << i * j;
}
cout << endl;
}
return 0;
}
效果
递归
阶乘
int Factorial(int n)
{
if (n = = 0)
return 1;
else
return n * Factorial(n - 1);
}
逆输出
#include <iostream>
using namespace std;
void reverse()
{
char ch; // 局部量
cin >> ch;
if (ch != '.')
reverse();
cout << ch;
}
int main()
{
reverse();
}
汉诺塔
// 汉诺塔
void hanoi(int n, char a, char b, char c)
{
if (n >= 1)
{
hanoi(n - 1, a, c, b);
cout << a << " --> " << c << endl;
hanoi(n - 1, b, a, c);
}
}
int main()
{
int m;
cout << " Input the number of diskes: " << endl;
cin >> m;
hanoi(m, 'A', 'B', 'C');
}
class6跳转语句
break
#include <iostream>
using namespace std;
int main()
{
//break
//1.switch副本难度
cout << "请选择副本难度" << endl;
cout << "1:普通难度" << endl;
cout << "2:中等难度" << endl;
cout << "3:困难难度" << endl;
int select = 0;
cin >> select;
switch (select)
{
case 1:
cout << "nomal" << endl;//不加break会一直执行所有case
break;
case 2:
cout << "middle" << endl;
break;
case 3:
cout << "hard" << endl;
default:
break;
}
return 0;
}
continue
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 100;i++)
{
if (i % 2 == 0)
{
continue;//可以筛选条件,执行到此就不在向下执行,执行下一次循环
//break会退出循环
}
cout << i << endl;
}
return 0;
}
goto
使用建议:不建议使用
class7一维数组
数组名和定义
#include <iostream>
using namespace std;
//数组应该放在一块连续的内存空间中,每个元素都是相同的数据类型
int main()
{
//数组的三种定义方法:
/*
1.数据类型 数组名[数组长度];
2.数据类型 数组名[数组长度]={值1.值2...};
3.数据类型 数组名[ ]={值1.值2...};(必须要定义初始长度)
*/
int arr[5] = { 10,20,30,40 };//arr[5]表示有5个值,但是arr[0]是第一个值,缺少的值由0填充
for (int i=0;i < 5; i++)
{
cout << arr[i] << endl;
}
cout <<"统计数组占用内存的大小:"<< sizeof(arr) << endl;
cout << "统计数组首地址:" << arr << endl;
cout << (int)arr << endl;//强转16进制为10进制
cout << "统计数组第一个元素的首地址:" << (int)&arr[0] << endl;
cout << "统计数组第一个元素的首地址:" << (int)&arr[1] << endl;//差四个字节
//sizeof(arr)/sizeof(arr[0])-1=元素个数
//数组名是个常量,不可再赋值
return 0;
}
案例一 五只小猪称体重
#include <iostream>
using namespace std;
int main()
{
int arr[] = {300, 350, 200, 400, 250};
int max = 0;
for (int i = 0; i<5; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
cout <<"最重的小猪为:" << max << endl;
return 0;
}
案例二 元素逆置
重点学习对换数值三步法
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 300, 350, 200, 400, 250 };
for (int i = 0; i < 5; i++)
{
cout <<"first:" << arr[i] << endl;
}
int start = 0;
int end = sizeof(arr)/sizeof(arr[0])-1;
while(start < end)
{
int a = arr[start];//三步走,对换数值
arr[start] = arr[end];
arr[end] = a;
start++; end--;
}
for (int i = 0; i < 5; i++)
{
cout <<"then:"<< arr[i] << endl;
}
return 0;
}
冒泡排序
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 4,2,8,0,5,7,1,3,9 };
cout << "冒泡排序前:" << endl;
for (int i = 0; i < 9; i++)
{
cout << arr[i];
}
cout << endl;
int end = sizeof(arr) / sizeof(arr[0])-1;//外循环:进行排序工作,排序的总次数=元素的个数-1
for (int i = 0; i < end; i++)
{
for (int j = 0; j < end - i; j++)//内循环:进行数组内的排序,对比次数
{
if (arr[j] > arr[j + 1])
{
int a = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = a;
}
}
}
cout << "冒泡排序后:" << endl;
for (int i = 0; i < 9; i++)
{
cout << arr[i];
}
return 0;
}
效果
二维数组
二维数组的定义方式&名称的用途
#include <iostream>
using namespace std;
int main()
{
//二维数组的定义方式
/*定义:
数据类型 数组名[行][列];
* 数据类型 数组名[行][列] = {{数据1,数据2},{数据3,数据4}};
数据类型 数组名[行][列] = {数据1,数据2,数据3,数据4};
数据类型 数组名[][列] = {数据1,数据2,数据3,数据4};
*/
int arr[2][3] =
{
{1,2,3},
{4,5,6}
};
//int arr[ ][3] = {1, 2, 3, 4, 5, 6};可以没有行数,必须要有列数
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
//二维数组名称的用途
cout << "二维数组所占用的内存空间:" << sizeof(arr) << endl;
cout << "二维数组第一行所占用的内存空间:" << sizeof(arr[0]) << endl;
cout << "二维数组第一行第一个数据所占用的内存空间:" << sizeof(arr[0][0]) << endl;
//用来算行数和列数,用来访问
cout << "二维数组的首地址/第一行的首地址:" << (int)arr << endl;//每次随机分配
cout << "二维数组的第一个数的首地址:" << (int)&arr[0][0] << endl;//&为取值符,取具体数据地址
return 0;
}
应用案例——考试成绩统计
#include <iostream>
using namespace std;
//#include <string>
int main()//统计每个人的总分
{
int scores[3][3] =
{
{100,100,100},
{90,50,100},
{60,70,80}
};
string names[3] = { "张三","李四","王五" };
for (int i = 0; i < 3; i++)
{
int sum = 0;
for (int j = 0; j < 3; j++)
{
sum += scores[i][j];
//cout << scores[i][j] << " ";
}
//cout << "第 " << i + 1 << "个人的总分为:" << sum << endl;
cout << "" << names[i] << "的总分为:" << sum << endl;
}
}
class8函数
声名&类型
#include <iostream>
using namespace std;
/* 定义函数
返回值类型 函数名(参数列表)
{
函数语句;
return 表达式;
}
*/
//函数的声明
void nono();
void yesno(string a);
int noyes();
int add(int num1, int num2);
//函数类型
//1. 无参无反
void nono()
{
cout << "no constant,no return" << endl;
}
//2.有参无返
void yesno(string a)
{
cout << "a constant with no return" << endl;
}
//3.无参有返
int noyes()
{
cout << "i'll give you stn. u don't have,hold it:" << endl;
return 1000;
}
//4.有参有返,eg.加法函数
int add(int num1, int num2)//num叫做形参,没有传入的值是没有实际值的
{
int num3 = num1 + num2;
return num3;
}
int main()
{
nono();
string str = "有参无返";
yesno(str);
int d = noyes();
cout << "what i give u is:" << d << endl;
int a = 2;
int b = 3;
int c = add(a, b);
cout <<"有参有返: "<< c;
}
各种常用函数的定义
int getMax2ints(int x, int y)
{
int max = 0;
if(x>y)
max = x ;
else
max = y ;
return max;
}
int get_max_3ints(int x, int y, int z)
{
int t = 0 ;
int temp = getMax2ints(x,y);
t = getMax2ints(temp,z);
return t;
}
float min(float x, float y)
{
return (x>y)?y:x;
}
void show(void)
{
cout << "hello" <<endl;
}
// apply N int heap
int* apply_heap_memory(int N)
{
int * p = NULL ;
p = new int[N];
if (p != NULL)
{
return p;
}
else
{
return p;
}
}
// int : return type: void float int char ; int*
// (int N ) : argument 形式参数 , int x, int y
int funt1(int N)
{ // function body : algorithm
// .....
cout << min(1.2 , 9.3) <<endl;
int *ppppp = apply_heap_memory(10000);
int result = 1;
for(int i=1;i<=N;i++)
{
result = result * i;
}
return result;
}
// strlen strcpy strcat strcmp gets puts
int main(int argc, char** argv)
{
// module!
cout << funt1( funt1(3) ) <<endl ; // 5 实际参数
// 6!
函数的分文件编写
add.h
#include <iostream>
using namespace std;
int add(int num1, int num2);
add.cpp
#include "add.h"
int add(int num1, int num2)//num叫做形参,没有传入的值是没有实际值的
{
int num3 = num1 + num2;
cout << "两数之和:" << num3;
return num3;
}
源.cpp
#include <iostream>
#include "add.h"
using namespace std;
//在.h的头文件里面放函数声明 并适当引用其他头文件;函数的定义放到.c文件里,并引用对应头文件。
int main()
{
int a = 3; int b = 3;
add(a, b);
return 0;
}
class9指针
基础知识
#include <iostream>
using namespace std;
int main()
{
//定义指针的语法
int a = 10;
int* p;//数据类型*指针变量名
p =&a;//用指针记录变量地址
/*void* 类型指针可以指向存储任意数据类型的地址。
void* 类型的指针表示该变量存储的是一个内存的地址,但该地址的对象数据类型并不知道。
指针也是变量,所以其本身也要占有一定的内存单元,所以指针也有地址。可以用&运算符取出指针的地址.
*/
//使用指针
*p = 1000; //指针前面加一个星号代表解引用,找到指针指向的内存的数据(间接访问一个内存)
cout << "a的地址:" << p<<endl;
cout << "a的内存数据(通过指针修改过后):" << *p << endl;
cout << "a的内存数据(通过指针修改过后):" << a<<endl;
cout << "sizeof(int *)" << sizeof(int*) << endl;
cout << "sizeof(double*)"<< sizeof(double*) << endl;//32位操作系统下,(x86)指针就是个只占四个字节的地址
cout << "sizeof(int *)" << sizeof(int*) << endl;//64位操作系统是×64
//空指针
//空指针用于给指针变量进行初始化
int* p1 = NULL; //你不知道应该指向哪里的时候指向空,但是无权使用和访问,因为0~255是系统占用空间
//野指针
// int* p = (int*)0x1100;这不是我们申请的空间,不可以访问
}
const常量指针&指针常量
#include <iostream>;
using namespace std;
int a = 0;
int b = 10;
int main()
{
//常量指针
const int* p = &a;
//可以改指针的指向,不可以改数据
//指针常量
int* const p1 = &b;
//可以改指针的数据,不可以改指向
//均不可改,只读
const int* const p3 = &a;
}
指针和数组
- 定义的同时赋初值
这种在定义数组的同时赋初值的方法,可以对数组集体初始化, - 给已定义的数组赋初值
在C++中数组的初始化是有严格的规定的,数组只有在定义时才能整体初始化,否则只能对各个元素进行初始化。对于已定义的数组只能对各个元素进行赋值。
#include <iostream>;
using namespace std;
int main()
{
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
int* p = arr;
//数组名
cout << "利用指针访问元素:" << *p << endl;
for (int i = 0; i < 10; i++)
{
cout << "利用指针遍历元素:" << *p << endl;
p++;//让指针向后偏移四个字节
}
}
##指针和函数(值传递和地址传递)
#include <iostream>;
using namespace std;
//创建函数的办法进行值传递
void swap01(int a, int b)
{
int c = b;
b = a;
a = c;
cout << "swap01a=" << a << endl;
}
void swap02(int* p1, int* p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main()
{
//1.创建函数的办法进行值传递
int a = 10;
int b = 20;
swap01(a, b);
cout << "a=" << a << endl;//不影响外测函数的值,修改的是形参
//2.地址传递
int *p1 = &a;
int *p2 = &b;
swap02(&a, &b);
cout << "a=" << a << endl;//影响外测函数的值,修改的是实参
}
##综合使用案例
#include <iostream>
using namespace std;
void bubbleSort(int *arr,int len)
{
int times = 0;
for (int i = 0; i < len - 1; i++)
{
for(int j=0;j<len -1-i;j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j+1];
arr[j + 1] = arr[j];
arr[j] = temp;
times += 1;
}
}
}
cout << "比较次数:" << times << endl;
}
int main()
{
int arr[10] = { 4,5,6,7,8,3,2,1,9,10 };
int len = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr,len);
for (int i = 0; i < 10; i++)
{
cout << " "<<arr[i];
}
cout << endl;
}
内存
C++语言将内存划分成全局数据区、代码区、栈区和堆区。其中堆区比较空闲,可以由程序通过动态内存分配的方式来申请和释放。堆内存申请
new运算符
C++中使用new运算符可以从堆上分配内存。使用new运算符分配空间必须是已定义的数据类型。new运算符会向系统申请足够的存储空间,如果申请成功,则返回该内存块的首地址;如果申请不成功,则返回零值。
使用new运算符的一般形式有下面几种:
形式1:指针变量名=new 类型标识符。
形式2:指针变量名=new 类型标识符(初始值)。
形式3:指针变量名=new 类型标识符[内存单元个数]。
形式1和形式2都是申请分配某一数据类型所占字节数的内存空间;但是形式2在内存分配成功后,同时将一初始值存放到该内存单元中;而形式3可以同时分配若干个内存单元,相当于形成一个动态数组。
delete运算符
使用new运算符分配的内存一定要释放,否则会产生系统内存泄漏。
#include <iostream>
using namespace std;
int main()
{
int* p = new int;//分配1个int的内存空间
delete p;//释放内存
int* p = new int[10];//分配10个int的内存空间
delete[] p;//释放内存
}
#include <iostream>
using namespace std;
void fun1(void); //function declaration
int ga =1000;
int* ApplyHeapMemory(int N);
void ReleaseHeapMemory(int* p);
void fun1(void)
{
ga++;
cout <<"adadad "<< ga <<endl;
}
//function prototype
//void motor_moveto(float x,float y);
//float get_robot_joint1();
int main(int argc, char** argv)
{
//motor_moveto(1.2,4);
//float angle1 = get_robot_joint1();
fun1();
ga++;
cout <<ga<<endl;
int* p1 = ApplyHeapMemory(100);
for(int i=0;i<100;i++)
{
p1[i] = i;
}
ReleaseHeapMemory(p1);
return 0;
}
//写一个函数,申请int heap空间,N个
// 4 parts:
int* ApplyHeapMemory(int N)
{
int *p = NULL;
p = new int[N];
if(p)
{
cout<<"Apply OK!" <<endl;
}
else
{
cout<<"Apply failed!" <<endl;
p = NULL;
}
return p;
}
// exception handling 异常处理
void ReleaseHeapMemory(int* p)
{
if(p)
{
delete []p;
}
else
{
cout <<"pointer illegal!"<<endl;
}
}
class10结构体
定义和创建
#include <iostream>
using namespace std;
/*通过结构体创建变量的方式有三种
struct 结构体名 变量名
struct 结构体名 变量名 = (成员1值,成员2值…)
定义结构体时顺便创建变量*/
struct Student
{ //成员列表
//姓名
string name;
//年龄
int age;
//分数
int score;
}s3;
//
int main()
{
// 一
struct Student s1;//创建结构体时可以省略关键字struct
s1.name = "张三";//给s1属性赋值,通过.访问结构体变量中的属性
s1.age = 18;
s1.score = 100;
cout << "name:" << s1.name << "age:" << s1.age << "score" << s1.score;
//二
struct Student s2 = { "李四",19,80 };
cout << "name:" << s2.name << "age:" << s2.age << "score" << s2.score;
//三
//定义结构体时顺便创建变量
s3.name = "王五";
s3.age = 20;
s3.score = 60;
cout << "name:" << s3.name << "age:" << s3.age << "score" << s3.score;
}
结构体数组
#include <iostream>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
int main()
{
//创建结构体数组
Student stuArr[3] =
{
{"张三",18,100 },
{"李四",20,90},
{ }
};
//给结构体里的元素赋值
//如果不知道具体元素可以之后再赋值
stuArr[2] = { "赵六",80,90 };
for (int i = 0; i < 3; i++)
{
cout << "name:" << stuArr[i].name << "age:" << stuArr[i].age << "score" << stuArr[i].score<<endl;
}
}
结构体指针
#include <iostream>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
int main()
{
//创建结构体数组
Student stu = { "张三",18,100 };
Student* p = &stu;
cout << p->age;//相当于(*p).age
}
结构体嵌套结构体
struct Student
{
string name;
int age;
int score;
};
struct Teacher
{
int id;
string name;
int age;
struct Student stu;
};
t.stu.age
结构体做参数函数
#include <iostream>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
void Printstruct(Student stu)
{
cout << "name:" << stu.name << "age:" << stu.age << "score" << stu.score << endl;
}
void Printstruct2(Student *p)
{
cout << "name:" << p->name << "age:" << p->age << "score" << p->score << endl;
}
int main()
{
//创建结构体数组
Student stu = { "张三",18,100 };
Printstruct(stu);
Printstruct2(&stu);//将函数中的形参改成指针,可以减少内存空间,而且不会复制新的副本出来。
}
结构体中使用const
#include <iostream>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
void Printstruct2( const Student *p)
{//p->name=20;这个操作会报错,只读操作
cout << "name:" << p->name << "age:" << p->age << "score" << p->score << endl;
}
int main()
{
//创建结构体数组
Student stu = { "张三",18,100 };
Printstruct2(&stu);
}
案例-嵌套结构体输出
#include<iostream>
#include<string>
#include<ctime>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
struct Teacher
{
string name;
struct Student sArry[5];
};
void inPutInformation(struct Teacher tArry[], int len)
{
string Name = "ABCDE";
for (int i = 0; i < len; i++)
{
tArry[i].name = "Teacher_";
tArry[i].name += Name[i];
for (int j = 0; j < 5; j++)
{
tArry[i].sArry[j].name = "Student_";
tArry[i].sArry[j].name += Name[j];
int random = rand()% 60 +40;
tArry[i].sArry[j].score = random;
}
}
}
void printInformation(struct Teacher tArry[],int len)
{
for (int i = 0; i < len; i++)
{
cout << "老师的姓名:" << tArry[i].name << endl;
for (int j = 0; j < 5; j++)
{
cout << "\t学生的姓名:" << tArry[i].sArry[j].name << "考试分数:" << tArry[i].sArry[j].score << endl;
}
}
}
int main(void)
{
srand((unsigned int)time(NULL));
struct Teacher tArry[3];
int len = sizeof(tArry) / sizeof(tArry[0]);
inPutInformation(tArry,len);
printInformation(tArry,len);
system("pause");
return 0;
}
效果
案例-结构体数组排序
#include <iostream>
using namespace std;
struct Hero
{
string name;
int age;
string attribute;
};
void PrintByAge(Hero heroArry[],int len)
{
for (int i = 0; i < len; i++)
{
cout << heroArry[i].name << heroArry[i].age << heroArry[i].attribute << endl;
}
}
int main()
{
struct Hero heroArry[5] =
{
{"欣南",20,"火"},
{"东杉",24,"木"},
{"北淼",23,"水"},
{"坤中",18,"土"},
{"西昭",22,"金"},
};
int len = sizeof(heroArry) / sizeof(heroArry[0]);
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len - 1 - i; j++)
{
if (heroArry[j].age> heroArry[j+1].age)
{
Hero t = heroArry[j];
heroArry[j] = heroArry[j + 1];
heroArry[j + 1] = t;
}
}
}
PrintByAge(heroArry, 5);
效果
核心知识
内存分区模型
代码区:存放函数的二级制代码,由操作系统进行管理的
全局区:存放全局变量和静态变量以及常量
栈区:由编译器自动分配释放,存放函数的参数值,局部变量等
堆区: 由程序员分配和释放,若程序员不释放,程序结束时由操作系统回收
内存四区意义:不同区域存放的数据,赋予不同的声明周期,给我们更大的灵活编程
程序运行前
在程序编译后,生成了exe可执行文件,未执行该程序前分为两个区域。
代码区:
存放cpu执行的机器指令
代码区是共享的,共享的目的是对于频繁被执行的程序,只需要在内存中有一份打码即可
代码区是只读的,使其只读的原因是防止程序意外的修改了它的指令
全局区:
全局变量和静态变量存放于此
全局区还包含了常量区,字符串常量和其他常量也存放于此
该区域的数据在程序结束之后由操作系统释放
程序运行后
栈区:
由编译器自动分配释放,存放函数的参数值,局部变量等。
注意事项:不要返回局部变量的地址,栈区开辟的数据由编译器自动释放
堆区:
有程序员分配释放,若程序员不释放,程序结束之后有操作系统回收
在C++中主要利用new在堆区中开辟内存
int* p = new int(10);
new运算符
在堆区开辟数据
堆区开辟的数据,由程序员手动开辟,手动释放,释放用delete
语法:
利用new创建的数据,会返回该数据对应类型的指针
int* p = new int(10);//分配一个整型,值为10,p指向它
int* arry = new int[10];//分配一个10个int的数组;返回指向第一个元素的指针
delete p; //p必须指向一个动态分配的对象或为空
delete[] arry; //arry必须指向一个动态分配的数组或为空
引用
基本使用
作用:给变量起别名
语法:数据类型 &别名 = 原名
int a = 0;
int &b = a;
//a和b操作的是同一块内存
注意事项
引用必须初始化——告诉它它是谁的别名
引用在初始化之后,不可以改变
1. 做函数参数
作用:函数传参时,可以利用引用让形参修饰实参
优点:可以简化指针修改实参(传址)。
changeNums(int &a,int& b);//引用传递
int main(void)
{
int a = 10;
int b = 20;
changeNums(a,b);
//引用——其实上面的a就是下面a的一个别名
return 0;
}
2. 做函数的返回值
注意:不要返回局部变量引用
用法:函数调用作为左值
#include<iostream>
using namespace std;
int& test1()
{
int a = 10;//栈区
return a;
}
int& test2()
{
static int b = 20;//静态变量存放在全局区,全局区的数据在程序结束后系统释放
return b;
}
int main(void)
{
int& ret = test1();
int& ret2 = test2();
cout << ret2 << endl;
//作为左值
test2() = 1000;//如果函数的返回值是引用,这个函数调用可以作为左值
cout << ret2 << endl;
cout << ret << endl;//第一次结果正确是因为编译器做了保留
cout << ret;//第二次结果错误是因为a的内存已经释放
return 0;
}
3.引用本质
本质:引用的本质在c++内部实现是一个指针常量,引用一旦被初始化之后就不能更改。
非常量引用的初始值必须是左值,典型错误int &ref = 10;引用必须引一块合法的内存空间
void func(int& ref)
{
ref = 100;//ref是引用,转换为*ref = 100
}
int main(void)
{
int a = 10;
int &ref = a;//自动转化int* const ref = &a;//指针常量是指针指向不可改,也说明为什么引用不可更改
ref =20;//自动发现ref是引用,自动转换为*ref = 20;
}
4.常量引用
作用:常量引用主要用来修饰形参,防止误操作
//常量引用
//使用场景,用来修饰形参,防止误操作
//引用必须引用一块合法的内存空间
const int& ref = 10;
//加上const之后,编译器将代码修改为int temp =10;
//int& ref = temp;
//加入const之后变为只读不可以修改
5.在函数形参列表中,可以加const修饰形参,防止形参改变实参
void showvaL(const int& ref){ }
函数提高
函数默认参数
在c++中函数形参列表中的形参是可以有默认值的。
语法:返回值类型 函数名(参数=默认值)
//函数的哪个参数被声明默认了,下面函数调用的时候就可以少传哪个参数,如果有默认值还传了参数,用的就是函数调用传递的参数
int func(int a,int b =10,int c =23)
{
return a+b+c;
}
int main(void)
{
int ref = func(10);
return 0;
}
注意事项:如果某个位置已经有了默认参数,那么从这个位置往后都要有默认参数
//从b开始往后一的参数都有默认参数
int fun2(int a,int b= 10;int c =20)
{
}
如果函数的声明有默认参数,函数的实现就不能有默认参数了。
声明和实现只能有一个有默认参数。
int fun3(int a = 10;int b = 20);
int fun3(int a,int b)
{
}
函数重载
作用:函数名可以相同,提高复用性
函数重载满足条件
- 同一个作用域下
- 函数名相同
- 函数参数类型不同,或者个数不同,或者顺序不同
注意:
1 函数的返回值不可以作为函数重载的条件
2引用作为函数重载条件
3函数重载碰到函数默认参数
#include<iostream>
using namespace std;
void func(int &a)
{
//int& a =10;不合法
}
void func(const int &a)
{
//const int& a =10;合法——编译器自动优化
}
int main(void)
{
func(10);//调用第二个函数
return 0;//想要调用第一个,应该用int a=10;func(a);
}
#include<iostream>
using namespace std;
void func(int a ,int b = 10)
{
}
void func(int a)
{
}
int main(void)
{
func(10);
/*当函数重载碰到默认参数
编译器傻了,不知道该调用哪个了
——出现二义性
——写函数重载就不要加默认参数,避免这种情况的出现*/
return 0;
}
内联函数
inline int smallf()
{
……
}
int main()
{
……
a = smallf();
……
}
inline double volume(double, double);// 函数原型声明
int main()
{
double vol, r, h;
cin >> r >> h;
vol = volume(r, h);
cout << "Volume = " << vol << endl;
}
double volume(double radius, double height)
{
return 3.14 * radius * radius * height;
}
class11类和对象
设计一个类
- 类的成员变量不能在定义时进行初始化,也有直接int a=10;不过注意这种写法是c++11以后才有的
- 类的构造函数不能有返回值
- 类的析构函数不能有参数,也不可以发生重载
- 结构体struct的默认权限是公共的
类class的默认权限是私有的,类外不可访问
#include <iostream>
using namespace std;
const double pi = 3.14;
//class代表要设计一个类
class Circle//设计一个圆类
{
//访问权限
public://公共权限
//属性
int r; //半径
//行为
double calculateC()
{
return 2 * pi * r;
}
};
class Student
{
//访问权限
public://公共权限
//属性 成员属性 成员变量
string name;
double id;
//行为 成员函数 成员方法
void SendPrint() {
cout << "input stu's name&id:" << endl;
cin >> name;
cin >> id;
id = (double)id;
cout << "here's the stu's name&id:" <<name<<"& " << id << endl;
}
};
int main()
{
//通过圆类 创建具体的圆(对象)
Circle c1;
c1.r = 10;
cout << "圆的周长" << c1.calculateC() << endl;
Student stu1;
cout.setf(ios::fixed, ios::floatfield);//十进制计数法,不是科学计数法
cout.precision(0);//保留0位小数
stu1.SendPrint();
}
老师的
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
string s_Name;
int s_Id;
void showStudent()
{
cout << "姓名: " << s_Name << "ID:" << s_Id << endl;
}
//赋值
void inputName(string name)
{
s_Name = name;
}
};
int main(void)
{
Student s1;
//s1.s_Name = "张三";
s1.inputName("赵六");
s1.s_Id = 123456;
s1.showStudent();
return 0;
}
效果
访问权限—成员属性设置为私有
public——公共权限——成员类内可以访问,类外可以访问
protected–保护权限——成员类内可以访问,类外不可以访问
private——私有权限——成员类内可以访问,类外不可以访问
struct默认权限为公共public
class默认权限为私有private
成员属性设置为私有
优点1:将所有成员属性设置为私有,可以自己控制读写权限。
优点2:对于写权限,我们可以检测数据的有效性。
#include <iostream>
using namespace std;
class Person {
public:
//给只读数据提供可读课写接口
//1.设置姓名
void setName(string name)
{
m_name = name;
}
//2.获取姓名
string getName()
{
return m_name;
}
//给只读数据提供访问接口
//只有get没有set 只可访问不可更改赋值
int getAge()
{
m_age = 18;//不可赋值,但是要用,在内部初始化
return m_age;
}
//防止赋值错误
/*int setAge(int age)
{
if (age > 100) {
cout << "u kidding?" << endl;
return;
}
m_age = age;
}*/
private:
string m_name;
int m_age;
string m_mate;
};
int main()
{
Person p1;
//p1.m_name = "lisa";
p1.setName("lisa");
cout << "p1's name is " << p1.getName() << endl;
cout << "p1's age is " << p1.getAge() << endl;
}
设计立方体类
#include <iostream>
using namespace std;
class cube {
public:
//赋值获取长宽高
void setl(int l)
{
c_l = l;
}
void setw(int w)
{
c_w = w;
}
void seth(int h)
{
c_h = h;
}
int getl()
{
return c_l;
}
int getw()
{
return c_w;
}
int geth()
{
return c_h;
}
//获取立方体面积&体积
int calcuS()
{
return 2*(c_l * c_h + c_h * c_w + c_l * c_w);
}
int calcuV()
{
return c_h * c_w * c_l;
}
//成员函数判断是否相等
bool issamebyClass(cube& c)//只用传一个函数!!!
{
if (c_h == c.geth() && c_l == c.getl() && c_w == c.getw())
{
return true;
}
return false;
}
private:
int c_l;
int c_w;
int c_h;
};
bool isSame(cube& c1, cube& c2)
{
if (c1.geth() == c2.geth() && c1.getl() == c2.getl() && c1.getw() == c2.getw())
{
return true;
}
return false;
}
int main()
{
cube c1;
c1.seth(10);
c1.setl(10);
c1.setw(10);
cout << c1.calcuS() << endl;
cout << c1.calcuV() << endl;
cube c2;
c2.seth(10);
c2.setl(10);
c2.setw(10);
//利用全局函数判断
bool ret = isSame(c1, c2);
{
if(ret)
{
cout << "利用全局函数,c1和c2相等" << endl;
}
else
{
cout << "利用全局函数,c1和c2不相等" << endl;
}
}
//成员函数判断是否相等
bool ret2 = c1.issamebyClass(c2);
if (ret2)
{
cout << "利用成员函数,c1和c2相等" << endl;
}
else
{
cout << "利用成员函数,c1和c2不相等" << endl;
}
system("pause");
return 0;
}
设计点和圆的关系类
#include<iostream>
using namespace std;
class Point
{
public:
void setx(int x)
{
c_x = x;
}
int getx()
{
return c_x;
}
void sety(int y)
{
c_y = y;
}
int gety()
{
return c_y;
}
//建议将属性设置为私有,对外提供接口
private:
int c_x;
int c_y;
};
class Circle
{
public:
void setr(int r)
{
c_R = r;
}
int getr()
{
return c_R;
}
void setcenter(Point center)
{
c_center = center;
}
Point getcenter()
{
return c_center;
}
private:
int c_R;
Point c_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
{
cout << "点在圆内" << endl;
}
}
int main(void)
{
Circle c1;
c1.setr(10);
Point center;
center.setx(10);
center.sety(10);
c1.setcenter(center);
Point p1;
p1.setx(3);
p1.sety(4);
//调用判断
isInCircle(c1, p1);
return 0;
}
不经过只读处理的
#include<iostream>
using namespace std;
class Point
{
public:
int c_x;
int c_y;
};
class Circle
{
public:
int c_R;
Point c_center;
};
//判断
void isInCircle(Circle &c,Point &p)
{
int distance =
(c.c_center.c_x-p.c_x) * (c.c_center.c_x-p.c_x) +
(c.c_center.c_y-p.c_y) * (c.c_center.c_y-p.c_y);
int rdistance = c.c_R * c.c_R;
if (distance == rdistance)
{
cout << "点在圆上" << endl;
}
else if (distance > rdistance)
{
cout << "点在圆外" << endl;
}
else
{
cout << "点在圆内" << endl;
}
}
int main(void)
{
Circle c1;
c1.c_R=10;
Point center;
c1.c_center.c_x=10;
c1.c_center.c_y = 10;
Point p1;
p1.c_x=10;
p1.c_y=10;
//调用判断
isInCircle(c1, p1);
return 0;
}
分文件编写
point.h
#pragma once
#include<iostream>
using namespace std;
class Point
{
public:
void setx(int x);
int getx();
void sety(int y);
int gety();
private:
int c_x;
int c_y;
};
point.cpp
#include"point.h"
//Point::告诉编译器这是Point作用域下面的一个成员函数
void Point::setx(int x)
{
c_x = x;
}
int Point::getx()
{
return c_x;
}
void Point::sety(int y)
{
Point::c_y = y;
}
int Point::gety()
{
return c_y;
}
circle.h
#pragma once
#include<iostream>
#include "point.h"
using namespace std;
class Circle
{
public:
void setr(int r);
int getr();
void setcenter(Point center);
Point getcenter();
private:
int c_R;
Point c_center;
};
circle.cpp
#include<iostream>
#include "circle.h"
#include "point.h"
void Circle::setr(int r)
{
c_R = r;
}
int Circle::getr()
{
return c_R;
}
void Circle::setcenter(Point center)
{
c_center = center;
}
Point Circle::getcenter()
{
return c_center;
}
cpp
#include<iostream>
#include "circle.h"
#include "point.h"
using namespace std;
//判断
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
{
cout << "点在圆内" << endl;
}
}
int main(void)
{
Circle c1;
c1.setr(10);
Point center;
center.setx(10);
center.sety(10);
c1.setcenter(center);
Point p1;
p1.setx(3);
p1.sety(4);
//调用判断
isInCircle(c1, p1);
return 0;
}
构造函数和析构函数(对象的初始化清理)
在生活中我们所购买的点子产品大多都有恢复出厂设置,在某一天我们不使用的时候清楚自己的数据来保证自己信息的安全。
C++中的面向对象来源生活,每个对象也会有初识设置以及对象销毁前的清理数据的设置。
构造函数和析构函数
对象的初始化和清理也是两个非常重要的安全问题。
一个对象或者变量没有初识状态,对其使用后的后果是未知的。
同样的使用完一个对象或者变量,没有及时进行清理,也会造成一定的安全问题。
C++利用了构造函数和析构函数解决上述问题,这两个函数将会被编译器自动调用,完成对象初始化和清理工作。
对象的初始化和清理工作是编译器强制要我们做的事情,因此如果我们不提供构造和析构,编译器会提供,但是编译器提供的构造函数和析构函数是空实现。
构造函数:主要作用在于创建对象时为对象的成员属性赋值,构造函数由编译器自动调用,无须手动调用。
析构函数:主要作用在于对象销毁前系统自动调用,执行一些清理工作。
#include <iostream>
using namespace std;
//对象的初始化和清理
//构造函数 进行初始化操作
//析构函数 进行清理操作
class Person
{
public:
Person()//构造函数,甚至不需要写void
{
cout << "调用构造函数Person" << endl;//不写这行代码,系统会自动调用一次这个函数,只不过是空函数
}
~Person()
{
cout << "调用析构函数Person" << endl;//对象在被销毁前,会自动调用析构函数一次
}
};
void tesr01()
{
Person p;//创建了一个对象,但是没有特意调用Person(),构造函数也会被执行
}
int main()
{
tesr01();
}
函数的分类和调用
#include <iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "调用构造函数Person(无参构造)" << endl;
}
Person(int a)
{
age = a;
cout << "调用构造函数Person(有参构造)" << endl;
}
//拷贝构造函数
Person(const Person &p)
{
age = p.age;
cout << "调用构造函数Person(拷贝构造)" << endl;
}
~Person()
{
cout << "调用析构函数Person" << endl;
}
int age;
};
//调用
void tesr01()
{
//1、括号法
Person p1;//创建对象,不可以加小括号,否则会被认为是在声明函数
Person p2(18);
Person p3(p2);
cout << "age p2:" <<p2.age<< endl;
cout << "age p3:" <<p3.age<< endl;
//2.显示法
/*Person p1;
Person p2=Person(18);
Person p3=Person(p2);*/
//Person(18);//单独拿出来即是匿名对象:当前行执行结束后,系统会立即回收掉匿名对象,即清除(运行析构函数)
//不要利用拷贝构造函数初始化匿名对象,否则会是重定义
//3.隐式转化法
//Person p2 = 18;
}
int main()
{
tesr01();
}
拷贝构造函数的调用时机
C++中拷贝构造函数调用时机通常有三种情况
- 使用一个已经创建完毕的对象来初始化一个新对象
- 值传递的方式给函数参数传值
- 以值方式返回局部对象
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "Person的默认构造函数调用" << endl;
}
Person(int age)
{
cout << "Person的有参构造函数调用" << endl;
m_Age = age;
}
Person(const Person& p)
{
cout << "Person的拷贝构造函数调用" << endl;
m_Age = p.m_Age;
}
~Person()
{
cout << "Person的析构函数调用" << endl;
}
int m_Age;
};
//使用一个已经创建完毕的对象来初始化一个对象
void test01()
{
Person p1(20);
Person p2(p1);
cout << "p2的年龄为" << p2.m_Age << endl;
}
//值传递的方式给函数参数传值
void dowork(Person p)
{
}
void test02()
{
Person p;
dowork(p);
}
//值方式返回局部对象
Person dowork2()
{
Person p1;//p1_a
cout << (int*)&p1 << endl;
return p1;//p1_2
}
void test03()
{
Person p = dowork2();//接受的是p1的拷贝p1_2
cout << (int*)&p << endl;
}
int main(void)
{
//test01();
//test02();
test03();
system("pause");
return 0;
}
构造函数的调用规则
#include<iostream>
using namespace std;
//构造函数的调用规则
//只要创建一个类,c++编译器会默认给每个类都添加至少3个函数
/*默认构造(空实现)
析构函数(空实现)
拷贝函数*/
class Person
{
public:
Person()
{
cout << "Person的默认构造函数调用" << endl;
}
Person(int age)
{
m_Age = age;
cout << "Person的有参构造函数调用" << endl;
}
Person(const Person& p)
{
m_Age = p.m_Age;
cout << "Person的拷贝构造函数调用" << endl;
}
~Person()
{
cout << "Person的默认析构函数调用" << endl;
}
int m_Age;
};
void test()
{
Person p;
p.m_Age = 18;
Person p2(p);
cout << "p2的年龄为" << p2.m_Age << endl;
}
//当用户创建了有参构造函数,编译器就不再提供默认无参构造函数,但是会提供默认拷贝构造函数
//如果用户定义拷贝构造函数,C++不会再提供其他构造函数
void test02()
{
}
int main(void)
{
test02();
system("pause");
return 0;
}
深拷贝与浅拷贝
#include<iostream>
using namespace std;
//深拷贝与浅拷贝问题
class Person
{
public:
Person()
{
cout << "Person的默认构造函数调用" << endl;
}
Person(int age,int height)
{
m_Height = new int(height);
m_Age = age;
cout << "Person的有参构造函数调用" << endl;
}
/* 错误 Person(const Person& p)
{
cout << "Person的拷贝构造函数调用" << endl;
m_Age = p.m_Age;
//浅拷贝
m_Height = p.m_Height;编译器默认实现的就是这行代码
}*/
Person(const Person& p)
{
cout << "Person的拷贝构造函数调用" << endl;
m_Age = p.m_Age;
//深拷贝操作
m_Height = new int(*p.m_Height);
}
~Person()
{
//将堆区开辟的数据进行释放
if (m_Height !=NULL)
{
delete m_Height;
m_Height = NULL;
}
cout << "Person的析构构造函数调用" << endl;
}
int m_Age;
int* m_Height;//为什么要用指针——要把身高开辟到堆区
};
void test()
{
Person p1(18,166);
cout << p1.m_Age<<"\t" << *p1.m_Height << endl;
Person p2(p1);
cout << p2.m_Age<<"\t" <<*p2.m_Height<< endl;
}
int main(void)
{
test();
system("pause");
return 0;
}
初始化列表
C++提供了初始化列表语法,用来初始化对象。
语法
构造函数():属性1(值1),属性2(值2)…{}
派生类构造函数的初始化列表中包含 :初始化基类数据成员、新增内嵌对象数据及新增一般成员数据所需要的全部参数。
#include<iostream>
using namespace std;
class Person
{
public:
//传统赋值操作
/*Person(int a, int b, int c)
{
m_A = a;
m_B = b;
m_C = c;
}*/
//初始化列表初始化属性
Person(int a,int b,int c) :m_A(a), m_B(b), m_C(c)
{
}
int m_A;
int m_B;
int m_C;
};
void test()
{
//Person p(10,20,30);
Person p(30,20,10);
cout << p.m_A << endl;
cout << p.m_B << endl;
cout << p.m_C << endl;
}
int main(void)
{
test();
system("pause");
return 0;
}
class D {
int a, b;
string c;
public:
D() : a(1), b(2), c("sss") {
cout<<"a is: "<<a<<endl;
cout<<"b is: "<<b<<endl;
cout<<"c is: "<<c<<endl;
}
};
类对象作为类成员
当其他类的对象作为本类的成员时,
构造时先构造其他类的对象,再构造自身。
自身的析构函数先进行,之后其它类再进行。
#include<iostream>
#include<string>
using namespace std;
class Phone
{
public:
Phone(string p)
{
Phonename = p;
cout << "Phone的构造函数调用" << endl;
}
~Phone()
{
cout << "Phone的析构函数调用" << endl;
}
string Phonename;
};
class Person
{
public:
//Phone Personphone = pname 隐式转换法
Person(string name, string pname):Personname(name), Personphone(pname)
{
cout << "Person的构造函数调用" << endl;
}
~Person()
{
cout << "Person的析构函数调用" << endl;
}
string Personname;
Phone Personphone;
};
void test()
{
Person p("张三", "华为");
cout << p.Personname<< endl;
cout << p.Personphone.Phonename<< endl;
}
int main(void)
{
test();
system("pause");
return 0;
}
静态成员
静态成员就是在成员变量和成员函数前面加上关键字啊static,称为静态成员。
静态成员分为:
静态成员变量
1.所有对象共享同一份数据
2.在编译阶段分配内存
3.类内声明,类外初始化
#include<iostream>
using namespace std;
class Person {
public:
//所有对象都共享同一份数据,只要有人更改了数据,就会更改静态成员变量数值
static int m_a;
//静态成员变量也还是有访问权限的
private:
static int m_b;
};
int Person::m_a = 100;//类外初始化变量
int Person::m_b = 20;//类外无法访问m_b
void test01()
{
//静态成员变量不属于某个对象上,所有对象共享同一份数据
//1,通过对象访问静态成员变量
Person p;
cout << p.m_a << endl;//100
Person p2;
p2.m_a = 200;
cout << p2.m_a << endl;//200
//2.通过类名进行访问
cout << Person::m_a << endl;//200
}
int main()
{
test01();
}
静态成员函数
1.所有成员共享同一个函数
2.静态成员函数只能访问静态成员变量
#include<iostream>
using namespace std;
class Person
{
public:
//静态成员函数
static void func()
{
age = 100;//静态的成员函数可以访问静态的成员变量,不可以访问非静态的成员变量
//无法区分到底是哪个对象的成员变量
cout << "static void func调用" << endl;
}
static int age;
//静态成员函数也是有访问权限的
private:
static void func()
{
}
};
void test01()
{
//两种访问方式
//通过对象访问
Person p;
p.func();
//通过类名也可以访问
Person::func();
//Person::func2();类外访问不到私有的静态成员函数
}
int main(void)
{
test01();
system("pause");
return 0;
}
C++对象模型和this指针
成员变量和成员函数分开存储
在C++中,类内的成员变量和成员函数分开存储,
只有非静态成员变量才属于类的对象上。
(只有非静态成员变量的大小算进类的大小中,其他的都不算。)
空对象的大小是1,为的是区分不同类在内存中的占用位置。
#include<iostream>
using namespace std;
//成员变量和成员函数是分开存储的
class Person
{
int m_A;//非静态成员属于类对象上的。
static int m_B;//静态的成员变量不属于类的对象上。
void func() {}//非静态成员函数不属于类的对象上
static void func2(){}//静态成员函数不属于类的对象上
};
int Person::m_B = 10;
void test01()
{
Person p;
//空对象占用内存空间为1
/*C++编译器给每个空对象也分配一个字节的空间,为的是区分空对象在占内存的位置,
没一个空对象也应该有一个独一无二的内存地址*/
cout << sizeof(p) << endl;
}
void test02()
{
Person p;
cout << sizeof(p) << endl;
}
int main(void)
{
test01();
test02();
system("pause");
return 0;
}
this指针
this指针的概念
通过上一个知识点《成员变量和成员函数是分开存储的》我们知道C++中成员变量和成员函数是分开存储的。
每一个非静态成员函数只会诞生一份函数实例,也就是说多个同类型的对象会公用一块代码。
那么问题是:这一块代码是如何区分是哪个对象调用自己的呢?
C++通过提供特殊的对象指针,this指针,解决上述问题。
this指针指向被调用的成员函数所属的对象。
(谁调的,this就指向谁)
this指针是隐含每个非静态成员函数内的一种指针。
this指针不需要定义,直接使用即可。
this指针的用途
1,当形参和成员变量同名时,可用this指针来区分
2,在类的非静态成员函数中返回对象本身,可使用return this
3,解决名称冲突
4,返回对象本身用this
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
//this指针指向的是被调函数的成员函数所属的对象
//这里指向的就是p
this->age = age;
}
//返回本体要用引用的方式进行返回
//这里返回值如果是Person,就创建了一个新的对象
Person& PersonAddPerson(Person &p)//&引用传递,去掉会变成值传递,值传递会导致拷贝构造函数,创建新的对象,返回的不是p2而是p2',无法一直链式累加
{
this->age += p.age;
return *this;//返回对象本身用*this,this是指向p2的指针
}
int age;//注意起名规范也可以解决名字冲突的问题
};
//解决对象冲突
void test()
{
Person p(18);
cout << p.age << endl;
}
//返回对象本身用*this
void test01()
{
Person p1(10);
Person p2(10);
p2.PersonAddPerson(p1);//将p1和p2的加在一起
//多次追加,return *this;
//链式编程思想
p2.PersonAddPerson(p1).PersonAddPerson(p1);
cout << p2.age << endl;
}
int main(void)
{
test01();
system("pause");
return 0;
}
空指针返回成员函数
C++中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针,如果用到this指针,需要加以判断来保证代码的健壮性。
#include<iostream>
using namespace std;
class Person
{
public:
void ShowClassName()
{
cout << "this is Person class" << endl;
}
void ShowPersonAge()
{
//提高健壮性,空的就直接返回,防止代码崩溃
if (this == NULL)
{
return;
}
//报错原因是因为传入的指针是NULL——无中生有,用一个空指针访问里面的属性
cout << this->m_Age << endl;
}
int m_Age;
};
void test()
{
Person* p = NULL;
p->ShowClassName();
p->ShowPersonAge();
}
int main(void)
{
test();
system("pause");
return 0;
}
const修饰成员函数
常函数:
成员函数后加const后我们称这个函数为常函数
常函数不可以修改成员属性
成员属性声明时加关键字mutable后,在常函数中依然可以修改
常对象:
声明对象前const称该对象为常对象。
常对象只能调用常函数。
#include<iostream>
using namespace std;
//常函数
class Person
{
public:
//this指针的本质是指针常量,指针的指向是不可以修改的
//就相当于Person *const this;
//const Person *const this;
//在成员函数后面加const修饰的是this指向,让指针指向的值也不可以修改
void showPerson() const//加个const就不允许修改了
{
this->m_b = 100;
//this->m_a=100;//常函数里面指针指向的值也不可以改
//this = NULL;this指针是不可以修改指针的指向的
}
int m_a;
mutable int m_b;//加了mutable修饰的特殊变量,即使在常函数,常对象中,也可以修改这个值
void func()
{
m_a = 100;//在普通成员函数中是可以修改的
}
};
void test()
{
Person P;
P.showPerson();
}
//常对象
void test1()
{
const Person p;//在对象前加const,变为常对象
//p.m_a = 100;
p.m_b = 100;
//常对象只能调用常函数
p.showPerson();
//p.func();常对象不能调用普通成员函数,因为普通成员函数可以修改属性。
}
int main(void)
{
test();
system("pause");
return 0;
}
友元
可客厅就是Public,你的卧室就是Private
客厅所有人都可以进去,但是你的卧室只有和你亲密的人可以进。
在程序中,有些私有属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元技术。
友元的目的就是让一个函数或者类 访问另一个类中的私有元素。
友元的关键字——friend
全局函数做友元friend void goodgay(Building* building);
#include<iostream>
#include<string>
using namespace std;
class Building
{
//goodgay全局函数是Building类的一个好朋友,可以访问你家的卧室(私有成员)
friend void goodgay(Building* building);
public:
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
public:
string m_SittingRoom;
private:
string m_BedRoom;
};
//全局函数
void goodgay(Building* building)
{
cout << "好基友全局函数正在访问你的" << building->m_SittingRoom << endl;
cout << "好基友全局函数正在访问你的" << building->m_BedRoom << endl;
}
void test()
{
Building building;
goodgay(&building);
}
int main(void)
{
test();
system("pause");
return 0;
}
类做友元friend class GoodGay;
一个类在另一个中friend class xx。
#include<iostream>
#include<string>
using namespace std;
//在前面先声明一下
class Building;
class GoodGay
{
public:
GoodGay();
public:
void visit();//参观函数 访问Building中的属性
Building* building;
};
class Building
{
//GoodGay是Building类的好朋友,可以访问其私有属性
friend class GoodGay;
public:
Building();
public:
string m_SittingRoom;
private:
string m_BedRoom;
};
//在类外写成员函数
Building::Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
//创建一个Building对象
building = new Building;
}
void GoodGay::visit()
{
cout << "好基友正在访问你的" << building->m_SittingRoom << endl;
cout << "好基友正在访问你的" << building->m_BedRoom << endl;
}
void test()
{
GoodGay gy;
gy.visit();
}
int main(void)
{
test();
system("pause");
return 0;
}
成员函数做友元friend void GoodGay::visit();
告诉编译器 另一个类中的xx成员函数作为本类的好朋友,可以访问私有函数。
#include<iostream>
#include<string>
using namespace std;
class Building;
class GoodGay
{
public:
GoodGay();
void visit();//可以访问Building中私有成员
void visit1();//不可以访问Building中私有成员
Building* builidng; //创建出来可以维护指针
};
class Building
{
//告诉编译器 GoodGay类中的visit成员函数作为本类的好朋友,可以访问私有函数
friend void GoodGay::visit();
public:
Building();
public:
string m_SittingRoom;
private:
string m_BedRoom;
};
Building::Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
builidng = new Building;//地址,building是指针,方便程序员在堆区避免空指针
}
void GoodGay::visit()
{
cout << "visit正在访问" << builidng->m_SittingRoom << endl;
cout << "visit正在访问" << builidng->m_BedRoom << endl;
}
void GoodGay::visit1()
{
cout << "visit1正在访问" << builidng->m_SittingRoom << endl;
}
void test()
{
GoodGay gg;
gg.visit();
gg.visit1();
}
int main(void)
{
test();
system("pause");
return 0;
}
运算符重载
运算符重载的概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。
加号运算符重载Person operator+(Person& p) 、Person operator+(Person& p1, Person& p2)
作用:实现两个自定义数据类型相加的运算。
例如:两个整型相加编译器知道该怎么进行运算,如果是两个自定义出来的类型,两个Person想加,编译器就不知道该怎么运算了。
#include<iostream>
#include<string>
using namespace std;
//加号运算符重载
class Person
{
public:
//1.成员函数重载+
/* Person operator+(Person& p)
{
Person temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
} */
int m_A;
int m_B;
};
//2.全局函数重载+
Person operator+(Person& p1, Person& p2)
{
Person temp;
temp.m_A = p1.m_A + p2.m_A;
temp.m_B = p1.m_B + p2.m_B;
return temp;
}
//函数函数重载版本
Person operator+(Person& p1, int num)
{
Person temp;
temp.m_A = p1.m_A + num;
temp.m_B = p1.m_B + num;
return temp;
}
void test01()
{
Person p1;
p1.m_A = 10;
p1.m_B = 10;
Person p2;
p2.m_A = 10;
p2.m_B = 10;
//成员函数重载本质调用
//Person p3 = p1.operator+(p2);
//Person p3 = p1 + p2;//可以简化成这种形式
//全局函数重载的本质调用
//Person p3 = operator+(p1,p2);
/*cout << p3.m_A << endl;
cout << p3.m_B << endl;*/
//运算符重载也可以发生函数重载
Person p3 = p1 + 10;
cout << p3.m_A << endl;
cout << p3.m_B << endl;
}
int main(void)
{
{
test01();
system("pause");
return 0;
}
总结:
对于内置的数据类型的表达式的运算符是不可能改变的
不要滥用运算符重载
左移运算符重载ostream& operator<<(ostream &cout, Person &p)
作用:可以输出自定义的类型
#include<iostream>
using namespace std;
class Person
{
friend ostream& operator<<(ostream& cout, Person& p);
public:
Person(int a, int b)
{
m_A = a;
m_B = b;
}
//利用成员函数重载左移运算符p.operator<<(cout)简化版本p<<cout
//一般我们不会利用成员函数来重载<<运算符,以为无法实现cout在左边
/*void operator<<(ostream &cout,Person &p)
{
cout << p.m_A << endl;
cout << p.m_B << endl;
}*/
private:
int m_A;
int m_B;
};
//只能利用全局函数来重载左移运算符
ostream& operator<<(ostream &cout, Person &p) //这样写的本质就是operator<<(cout,p)简化版本就是cout<<p;
{
cout << p.m_A << endl;
cout << p.m_B << endl;
return cout;
}
void test()
{
Person p(10,10);
cout << p << "hello world" << endl;
}
int main(void)
{
test();
system("pause");
return 0;
}
总结:重载左移运算符配合友元可以实现输出自定义数据类型。
递增运算符重载MyInteger& operator++()
作用:通过重载递增运算符,实现自己的整型数据。
#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)//这个int在这里作为占位参数,用来区分前置递增和后置递增
{
MyInteger temp = *this;
m_Num++;
return temp;
//后置递增要返回值,因为如果返回引用,这里相当于返回的是一个局部对象的引用。
//局部对象在当前函数执行完毕之后就被释放掉了,还要返回引用就是非法操作。
}
private:
int m_Num;
};
//全局函数重载左移运算符
ostream& operator<<(ostream& cout, MyInteger myint)
{
cout << myint.m_Num << endl;
return cout;
}
void test()
{
MyInteger myint;
cout << ++(++myint);
cout <<myint;
}
void test02()
{
MyInteger myint;
cout << myint++ << endl;
cout << myint << endl;
}
int main(void)
{
//test();
test02();
system("pause");
return 0;
}
赋值运算符重载Person& operator=(Person &p)
C++编译器至少给一个类添加4个函数(前三个之前已经讲过了)
默认构造函数(无参,函数体为空)
默认析构函数(无参,函数体为空)
默认拷贝构造函数,对属性进行值拷贝
赋值运算符operator=,对属性进行值拷贝
如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题。
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
m_Age = new int(age);
}
~Person()
{
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
}
//重载赋值运算符
Person& operator=(Person &p)
{
//编译器默认提供的是浅拷贝操作
//m_Age = p.m_Age;
//应该先判断是否有属性在堆区,如果有先释放干净,然后再深拷贝。
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
//深拷贝操作
m_Age = new int(*p.m_Age);
return *this;
}
int *m_Age;
};
void test1()
{
Person p1(18);
Person p2(20);
Person p3(30);
p3 = p2 = p1;
cout << *(p1.m_Age) << endl;
cout << *(p2.m_Age) << endl;
cout << *(p3.m_Age) << endl;
}
int main(void)
{
test1();
system("pause");
return 0;
}
关系运算符重载bool operator==(Person &p)
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
//重载==
bool operator==(Person &p)
{
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
{
return true;
}
else
{
return false;
}
}
bool operator!=(Person &p)
{
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
{
return false;
}
else
{
return true;
}
}
Person(string name, int age)
{
m_Name = name;
m_Age = age;
}
string m_Name;
int m_Age;
};
void test()
{
Person p1("张三", 20);
Person p2("张三", 20);
if (p1 == p2)
{
cout << "p1和p2是相等的" << endl;
}
else
{
cout << "p1和p2是不相等的" << endl;
}
if (p1 != p2)
{
cout << "p1和p2是不相等的" << endl;
}
else
{
cout << "p1和p2是相等的" << endl;
}
}
int main(void)
{
test();
system("pause");
return 0;
}
函数调用运算符重载int operator()(int a, int b)
函数调用运算符()也可以重载
由于重载后使用的方式非常像函数的调用,因此称为仿函数
仿函数没有固定写法,非常灵活
#include<iostream>
#include<string>
using namespace std;
//函数调用运算符重载
class MyPrint
{
public:
//重载函数调用运算符
void operator()(string text)
{
cout << text << endl;
}
};
class MyAdd
{
public:
int operator()(int a, int b)
{
return a + b;
}
};
void test()
{
MyPrint myprint;
myprint("hello world");
MyAdd myadd;
cout << myadd(1, 2) << endl;
//匿名函数对象——特点:当前行被执行完立即释放
cout << MyAdd()(100,100) << endl;
}
int main(void)
{
test();
system("pause");
return 0;
}
继承
继承的好处:减少重复代码
语法:class 子类:继承方式 父类
子类也称派生类
父类也称基类
派生类中的成员,包含量大部分
一类是从基类继承过来的,一类是自己增加的成员。
从基类继承过来的表现其共性,而新增加的成员体现其个性。
什么不可以被继承?
除了赋值运算符重载函数以外,所有的运算符重载函数都可以被派生类继承。
友元函数是不可以继承的,也就是说基类A的友元函数,并不能被继承到其派生类B中,也就是说A的友元函数不能访问B中自己所增加的成员(但是请注意,是不能访问B中新增加的成员,但是还可以访问B中的基类的成员的)。
派生类并不继承基类的构造和析构函数,只继承成员变量和普通成员方法。
尽管派生类不直接继承基类的构造和析构函数,有自己的构造和析构函数,但是派生类的构造函数一定会调用基类的某一个构造函数,析构函数也是一样。默认情况下派生类的默认构造函数调用的基类的默认构造函数,但是是派生类的任意构造函数也可以通过显式指定(语法是派生类构造函数:基类构造函数)来调用基类的任意一个构造函数(通过参数匹配的方式,类似于函数重载)。
——————————————本文为CSDN博主「stdcoutzrh」的原创文章,原文链接:https://blog.csdn/PecoHe/article/details/113177933
#include<iostream>
using namespace std;
class person
{
public:
string name;
int age;
//基类的默认构造函数
person(){cout<<"person()."<<endl;};
//基类的自定义构造函数
person(string Name,int Age):name(Name),age(Age){cout<<"person(string Name,int Age)."<<endl;};
//基类的默认析构函数
~person(){cout<<"~person()."<<endl;};
};
class man:public person
{
public:
bool male;
//派生类的默认构造函数,并且指定调用基类的默认构造函数
man():person(){cout<<"man():person()."<<endl;};
//派生类的自定义构造函数,并且指定调用基类的默认构造函数
man(bool male):person()
{
this->male=male;
cout<<"man(bool male):person()"<<endl;
};
//派生类的自定义构造函数,并且指定调用基类的自定义构造函数
man(string Name,int Age,bool Male):person(Name,Age)
{
this->male=Male;
cout<<"man(string name,int age,bool male):person(name,age)."<<endl;
};
~man(){cout<<"~man()."<<endl;};
};
eg1
#include<iostream>
#include<string>
using namespace std;
//公共页面
class BasePage
{
public:
void header()
{
cout << "首页、登录注册" << endl;
}
void footer()
{
cout << "帮助中心、交流合作" << endl;
}
void left()
{
cout << "java、python、c++" << endl;
}
};
//普通实现页面
//java页面
class Java : public BasePage
{
public:
void contenet()
{
cout << "java学科视频" << endl;
}
};
class Python : public BasePage
{
public:
void contenet()
{
cout << "python学科视频" << endl;
}
};
class Cpp : public BasePage
{
public:
void contenet()
{
cout << "c++学科视频" << endl;
}
};
void test()
{
cout << "java" << endl;
Java java;
java.header();
java.footer();
java.left();
java.contenet();
cout << endl;
cout << "python" << endl;
Python python;
python.header();
python.footer();
python.left();
python.contenet();
cout << endl;
cout << "cpp" << endl;
Cpp cpp;
cpp.header();
cpp.footer();
cpp.left();
cpp.contenet();
}
int main(void)
{
test();
system("pause");
return 0;
}
继承方式(有图)
#include<iostream>
using namespace std;
//公共继承
class Base1
{
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
class Son1 :public Base1
{
public:
void func()
{
m_A = 10;//父类中的公共权限成员,到了子类中依然是公共权限
m_B = 20;//父类中的保护权限成员,到了子类中依然是保护权限
//m_C = 10;父类中的隐私权限成员,子类访问不到
}
};
void test01()
{
Son1 son1;
son1.m_A = 100;
//son1.m_B = 100;保护权限的内容到了类外就无法访问了
};
//保护继承
class Base2
{
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
class Son2 :protected Base2
{
void func()
{
m_A = 100;//父类中公共权限的成员,因为是保护继承,到子类中变为保护权限
m_B = 100;//父类中保护权限的成员,保护继承后到了子类还是保护权限。
//m_C = 100;父类中的私有成员子类访问不到
}
};
void test02()
{
Son2 son2;
//保护权限类外访问不到,所以在son2中m_A也访问不到了
}
//私有继承
class Base3
{
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
class Son3:private Base3
{
void func()
{
m_A = 100;//父类中公共成员,私有继承后,到了子类变为私有成员
m_B = 100;//父类中保护成员,私有继承后,到了子类变为私有成员
//m_C = 100;父类的私有权限成员仍然访问不到
}
};
void test03()
{
Son3 son3;
//私有成员类外访问不到
}
//验证Son3私有继承后成员是否变成了私有属性
class GrandSon3 :public Son3
{
void func()
{
//访问不到父类的私有成员
//到了Son3中m_A,m_B,m_C全是私有成员,子类无法访问
}
};
int main(void)
{
system("pause");
return 0;
}
eg。私有继承
内部访问:
在Son内部访问
对象访问:
Son son;
son.func()//访问基类
#include<iostream>
using namespace std;
class Base { //声明基类
public:
void setx(int n)//正确,成员函数setx可以访问本类私有成员x
{
x = n;
}
void showx()//正确,成员函数showx可以访问本类私有成员x
{
cout << x << endl;
}
private:
int x;
public:
int xx;
};
class Derived :private Base {//声明Base的私有派生类Derived。
public:
void setxy(int n, int m)
{
setx(n);//基类的setx函数在派生类中为私有成员,派生类成员函数可以直接访问
y = m;//正确,成员函数showxy可以访问本类的私有成员y
}
void showxy()
{
cout << x;//错误,派生类成员函数不能直接访问基类的私有成员x。
cout << xx;//正确,派生类成员函数能直接访问基类的公有成员xx。
cout << y << endl;//正确,成员函数showxy可以访问本类的私有成员
}
private:
int y;
};
int main()
{
Derived obj;
obj.setx(10);//错误,setx在派生类中为私有成员,派生类对象不能访问。
obj.showx();//错误,showx在派生类中为私有成员,派生类对象能不能访问
obj.setxy(20, 30);//正确,setxy在类derived为公有成员,派生类对象能访问。
obj.showxy();//正确,showxy在类derived中为公有成员,派生类对象能访问
return 0;
}
继承中的对象模型&利用VS的开发人员命令提示工具查看对象模型
问题:从父类继承过来的对象,哪些属于子类对象?
父类中所有的非静态成员属性都会被子类继承下去。
父类中私有的成员属性是被编译器给隐藏了,因此访问不到,但是确实被继承下去了
😊😊
打开工具
跳转到你cpp文件所在的盘
cd文件目录下
输入命令:cl /d1 reportSingleClassLayout类名 文件名(tab快速实现)
成功查看所有
#include<iostream>
using namespace std;
//继承中的对象模型
class Base
{
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
class Son:public Base
{
public:
int m_D;
};
void test01()
{
//父类中所有的非静态成员属性都会被子类继承下去
//父类中私有的成员属性是被编译器给隐藏了,因此访问不到,但是确实被继承下去了
cout << "sizeof of son:" << sizeof(Son) << endl;//结果是16 = 12 + 4
}
int main(void)
{
test01();
system("pause");
return 0;
}
继承中构造和析构的顺序
子类继承父类后,当创建子类时,也会调用父类的构造函数。
问题:父类和子类的构造函数和析构顺序怎么样的呢?
先构造父类,再构造子类
先析构子类,再析构父类
创建子类对象的同时也会创建一个父类对象。
在继承机制下,当对象消亡时,编译系统先执行派生类的析构函数,然后才执行 派生类中子对象类的析构函数,最后执行基类的析构函数。
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << "父类的构造函数" << endl;
}
~Base()
{
cout << "父类的析构函数" << endl;
}
};
class Son:public Base
{
public:
Son()
{
cout << "子类的构造函数" << endl;
}
~Son()
{
cout << "子类的析构函数" << endl;
}
};
void test01()
{
Son son;
}
int main(void)
{
test01();
system("pause");
return 0;
}
继承同名成员处理方式
问题:当子类与父类出现同名的成员。如何通过子类对象,访问到子类或父类中同名的数据呢?
访问子类同名成员,直接访问即可
访问父类同名成员,需要加作用域
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
m_A = 100;
}
void func()
{
cout << "父类同名成员函数调用" << endl;
}
void func(int a)
{
cout << "父类同名重载成员函数调用" << endl;
}
int m_A;
};
class Son:public Base
{
public:
Son()
{
m_A = 200;
}
void func()
{
cout << "子类同名成员函数调用" << endl;
}
int m_A;
};
//同名成员属性处理方式
void test01()
{
Son son;
cout <<son.m_A<< endl;
//如果要通过子类对象访问到父类中的同名成员,需要加作用域。
cout <<son.Base::m_A<< endl;
}
//同名成员函数处理方式
void test02()
{
Son son1;
son1.func();//子
son1.Base::func();//父
//如果子类中出现和父类同名的成员函数
//子类的同名成员会隐藏掉父类中所有同名成员函数
//如果想要访问到父类中被隐藏的同名成员函数,需要加作用域
son1.Base::func(10);
}
int main(void)
{
test02();
system("pause");
return 0;
}
继承同名静态成员处理方式
问题:继承中同名的静态成员在子类对象上是如何进行访问的呢?
静态成员和非静态成员出现同名,处理方式 一致。
访问子类同名成员,直接访问即可
访问父类同名成员,需要加作用域
#include<iostream>
using namespace std;
class Base
{
public:
static void func()
{
cout << "父类静态成员函数调用" << endl;
}
static void func(int a)
{
cout << "父类静态成员重载函数调用" << endl;
}
static int m_A;
};
int Base::m_A = 100;
class Son:public Base
{
public:
static void func()
{
cout << "子类静态成员函数调用" << endl;
}
static int m_A;
};
int Son::m_A = 200;
//同名静态成员
void test()
{
//通过对象访问
Son son1;
cout << "通过对象访问" << endl;
cout << son1.m_A << endl;
cout << son1.Base::m_A << endl;
//通过类名访问
cout << "通过类名访问" << endl;
cout << Son::m_A << endl;
//第一个::代表通过类名方式访问,第二个::代表访问父类作用域下
cout << Son::Base::m_A << endl;
}
//同名静态函数
void test01()
{
//通过对象访问
Son son2;
cout << "通过对象访问" << endl;
son2.func();
son2.Base::func();
//通过类名访问
cout << "通过类名访问" << endl;
Son::func();
Son::Base::func();
//父类同名重载成员函数调用
//子类出现和父类同名的静态成员函数,也会隐藏掉父类中所有同名成员函数(重载)
//如果想访问父类中被隐藏的同名成员,需要加作用域
Son::Base::func(100);
}
int main(void)
{
test();
cout << "我是分割线------" << endl;
test01();
system("pause");
return 0;
}
总结:同名静态成员处理方式和非静态处理方式一样,只不过有两种访问的方式(通过对象和类名)。
多继承语法
#include<iostream>
using namespace std;
//多继承语法
class Base1
{
public:
Base1()
{
m_A = 100;
}
int m_A;
};
class Base2
{
public:
Base2()
{
m_A = 200;
}
int m_A;
};
//子类需要继承base1和base2
class Son:public Base1,public Base2
{
public:
Son()
{
m_C = 300;
m_D = 400;
}
int m_C;
int m_D;
};
void test01()
{
Son son1;
cout << sizeof(son1) << endl;//16
cout << "第一个父类的m_A:" << son1.Base1::m_A<<endl;
cout << "第二个父类的m_A:" << son1.Base2::m_A<<endl;
}
int main(void)
{
test01();
system("pause");
return 0;
}
菱形继承(虚继承)
菱形继承带来的主要问题是子类继承两份相同的数据,导致资源浪费以及毫无意义。
利用虚继承可以解决菱形继承问题——virtual
#include<iostream>
using namespace std;
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 = 18;
st.Tuo::m_Age = 28;
//当菱形继承,当两个父类拥有相同的数据,需要加作用域来区分
cout << st.Sheep::m_Age << endl;
cout << st.Tuo::m_Age << endl;
cout << st.m_Age << endl;
//这份数据我们知道,只有一份就可以了,菱形继承导致数据有两份,资源浪费
}
int main(void)
{
test01();
system("pause");
return 0;
}
文件操作
程序运行时,产生的数据都属于临时数据,程序一旦运行结束就会被释放。
通过文件可以将数据持久化。
C++中对文件进行操作需要包含头文件< Fstream>
文件类型分为两种:
1.文本文件-文件以文本的ASCII码形式存储在计算机中
2.二进制文件-文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂他们
操作文件的三大类
ofstream:写操作
ifstream:读操作
fstream:读写操作
文本文件
文本文件写文件
- 包含头文件——#include< fstream>
- 创建流对象——ofstream ofs;
- 打开文件——ofs.open(“文件路径”,打开方式)
- 写数据——ofs<<“写入的数据”;
- 关闭文件——ofs.close();
文件打开方式:
ios::binary | ios::out
#include<iostream>
#include<fstream>
using namespace std;
//文本文件写文件
void test01()
{
//1.包含头文件
//2.创建流对象
ofstream ofs;
//3.指定打开方式
ofs.open("test.txt", ios::out);//如果不指定文件路径,默认和你项目的文件路径一样
//4.写内容
ofs << "姓名:张三" << endl;
ofs << "性别:男" << endl;
ofs << "年龄:18" << endl;
//5.关闭文件
ofs.close();
}
int main(void)
{
test01();
system("pause");
return 0;
}
文本文件读文件
- 包含头文件——#include< fstream>
- 创建流对象——ifstream ifs;
- 打开文件并判断文件是否打开成功——ifs.open(“文件路径”,打开方式);
- 读数据——四种方式读取
- 关闭文件——ifs.close();
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void test01()
{
//1.包含头文件
//2.创建流对象
ifstream ifs;
//3.打开文件,并且判断是否打开成功
ifs.open("test.txt",ios::in);
if (!ifs.is_open())
{
cout << "文件打开失败了" << endl;
return;
}
//4.读数据
//第一种
/*char buf[1024] = { 0 };
while (ifs>>buf)
{
cout << buf << endl;
}*/
//第二种
/*char buf[1024] = { 0 };
while (ifs.getline(buf,sizeof(buf)))
{
cout << buf << endl;
}*/
//第三种
/*string buf;
while (getline(ifs,buf))
{
cout << buf << endl;
}*/
//第四种-不推荐
char c;
while ((c = ifs.get()) != EOF)//EOF——end of file
{
cout << c;
}
ifs.close();
}
int main(void)
{
test01();
system("pause");
return 0;
}
二进制文件
以二进制的方式对文件进行读写操作
打开方式主要为ios::binary
二进制文件写文件
二进制方式写文件主要利用流对象调用成员函数write
函数原型:
ostream& wirte(const char* buffer,int len);
参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数。
#include<iostream>
#include<fstream>
using namespace std;
//二进制写文件
class Person
{
public:
char m_Name[64];
int m_Age;
};
void test01()
{
//1.包含头文件
//2.创建头文件
ofstream ofs("person.txt", ios::out | ios::binary);
//3.打开文件
//ofs.open("person.txt",ios::out | ios::binary);
//4.写文件
Person p = { "张三",18 };
ofs.write((const char*)&p,sizeof(Person));
//5.关闭文件
ofs.close();
}
int main(void)
{
test01();
system("pause");
return 0;
}
二进制方式读文件
二进制方式读文件主要利用流对象调用成员函数read
istream& read(char * buffer,int len);
#include<iostream>
#include<fstream>
using namespace std;
//二进制读文件
class Person
{
public:
char m_Name[64];
int m_Age;
};
void test01()
{
//1.包含头文件
//2.创建流对象
ifstream ifs;
//3.打开文件&判读文件是否打开成功
ifs.open("person.txt", ios::in | ios::binary);
if (!(ifs.is_open()))
{
cout<<"打开失败"<<endl;
return;
}
//4.读文件
Person p;
ifs.read((char*)&p, sizeof(Person));
cout << "姓名:" << p.m_Name<<" " << "年龄:" << p.m_Age << endl;
//5.关闭文件
ifs.close();
}
int main(void)
{
test01();
system("pause");
return 0;
}
版权声明:本文标题:关修远的笔记(黑马程序员) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1728314080a1153360.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论