声明:由于量太大 有35000字 俺只能大概格式复制粘贴了 所以格式都差不多 哎~ 而且到后面会潦草很多。。。
正文开始
写程序的思路
-
分析题目(先看明白题)
-
设计算法(想想怎么写)
-
编写程序(敲代码)
-
运行测试样例(检查对错)
-
对了 交代码
-
错了 调试 返回第一第二步
首先要想编写 C++ 程序 必须先写出头文件
C++ 通用头文件:
#include<bits/stdc++.h>
using namespace std;
int main(){
return 0;
}拓展一下最短程序:
int main();没坐!这段程序是可以正常运行的。。。
在代码中:
#include<bits/stdc++.h>这句话是头文件 其中< >包的是头文件名称。注意:这个叫万能头文件 包含了大多数头文件,当然windows.h就没有在内…
还有 带.h的都是 C 语言头文件,C++ 也能使。
using namespace std;
是命名空间声明语句 用于引入库,std就是一个库,很方便的一个库,具体后面会讲。
int main()
是主函数,后面的大括号把代码给包了起来。计算机运行程序会识别到主函数,随后从他的大括号里的第一个语句开始执行。
return 0;
这句话是让主函数返回一个 。在英文中return本身就是返回的意思。
然后就可以在大括号里开始写程序了。(逐渐发病)
C++最基本操作
C++ 变量类型
在 C++ 中,变量类型决定了变量可以存储什么样的数据。不同类型的变量占用不同的内存空间,并且在操作时有不同的规则。了解这些类型是学习 C++ 编程的第一步。
整型( )
整型是最常见的数据类型之一,用于表示没有小数部分的数字。int 通常用于存储整数值,支持正数、负数和零。
int a = 10; // 整数 10
int b = -50; // 整数 -50长整型( )
long 类型用于存储比 int 更大的整数。long 的大小通常是 或 字节,取决于平台。
long a = 1234567890; // 大整数长长整型( )
long long 是一种长整型,专门用于存储更大的整数。它的范围比 long 类型更大。
long long a = 123456789012345LL; // 超大整数短整型( )
short 是一种用于存储较小整数的类型。它的大小通常为 字节。
short a = 100; // 小整数无符号整数( )
unsigned 是一种没有符号的整数类型,表示只能存储非负数。
unsigned int a = 3000000000; // 无符号整数对于 short、long 和 long long 类型,也可以使用 unsigned 进行扩展,只存储非负整数。
字符型( )
char 类型用于存储单个字符,它的大小通常是 字节( 位)。
char a = 'A'; // 存储字符 'A'浮点数类型(用于表示小数)
单精度浮点数( )
float 用于存储单精度的小数,它的存储空间通常为 字节。
float a = 3.14f; // 小数 3.14双精度浮点数( )
double 用于存储双精度的小数,它的存储空间通常为 字节。
double a = 3.141592653589793; // 更精确的小数长双精度浮点数( )
long double 提供比 double 更高的精度,但它的具体范围和精度可能会因编译器和平台的不同而有所不同。
long double a = 3.1415926535; // 更高精度其他常用数据类型
布尔型( )
bool 用于存储布尔值,即 true(真)或 false(假)。它只占用 字节。
bool isActive = true; // 逻辑值 true
bool isFinished = false; // 逻辑值 false字符串类型( )
std::string 是一个 C++ 标准库提供的类,用于存储和操作字符串。
#include <iostream>
#include <string> // 引入 string 库
int main() {
std::string name = "C++ 编程"; // 存储字符串
std::cout << "Hello, " << name << std::endl; // 输出字符串
return 0;
}空类型( )
void 是一种特殊的类型,表示没有类型。(后面俺就不写了 懂得都懂)
变量的声明和赋值
int a; // 声明一个整型变量 a
float b; // 声明一个浮点型变量 b然后,你可以给变量赋值:
a = 5; // 给变量 a 赋值为 5
b = 3.14; // 给变量 b 赋值为 3.14当然,你也可以在声明的同时赋值:
int a = 5; // 声明并赋值
float b = 3.14;(作者在写这个的时候觉得自己像弱智)
示例:
int age = 25; // 声明并初始化年龄为 25
float height = 1.75; // 声明并初始化身高为 1.75 米
char grade = 'A'; // 声明并初始化成绩为 A
string name = "张三"; // 声明并初始化姓名为 张三变量的作用域
变量在程序中有一个作用域,也就是它能被访问的范围。例如,如果你在一个函数中声明了一个变量,它只能在该函数内部使用,函数外部无法访问。
#include <iostream>
using namespace std;
int main() {
int a = 10; // a 只在 main 函数内部有效
cout << "a 的值是:" << a << endl;
return 0;
}C++ 输入输出
输入和输出是程序和用户进行交互的最常用方法。通过输入,程序可以获取用户的信息;通过输出,程序可以把结果展示给用户。(废话)
标准输入( )
在 C++ 中,我们通常用 cin 来获取用户的输入。cin 是标准输入流对象,可以从键盘接收数据。使用时,我们需要配合 >> 操作符来读取输入的数据并存储到相应的变量中。
例如:(// 叫做注释 后面会讲)
#include <iostream> // 引入标准输入输出库
using namespace std; // 使用标准命名空间
int main() {
int age; // 声明一个整型变量 age
cout << "请输入你的年龄:"; // 提示用户输入
cin >> age; // 获取用户输入的年龄并存储到变量 age 中
cout << "你的年龄是:" << age << endl; // 输出用户输入的年龄
return 0; // 返回 0,表示程序正常结束
}标准输出( )
cout 是标准输出流对象,用来将数据输出到屏幕。它常常配合 << 操作符使用,把数据传递给 cout,让程序在屏幕上显示。
#include <iostream>
using namespace std;
int main() {
cout << "祝作者寿比南山,福如东海" << endl; // 输出一段文本
return 0;
}顺序结构
顾名思义,就是按照顺序执行程序,这也是 C++ 中最简单的知识点了。
#include <iostream>
using namespace std;
int main() {
int x = 10; // 声明并初始化变量 x
int y = 20; // 声明并初始化变量 y
int result = x + y; // 计算 x 和 y 的和
cout << "x 和 y 的和是:" << result << endl; // 输出结果
return 0; // 返回 0,表示程序正常结束
}四、运算
C++ 支持多种运算,包括算数运算、比较运算、逻辑运算等。
算数运算
C++ 提供了几种常用的算数运算符:
#include <iostream>
using namespace std;
int main() {
int x = 7, y = 3;
cout << "x + y = " << x + y << endl; // 7 + 3 = 10
cout << "x - y = " << x - y << endl; // 7 - 3 = 4
cout << "x * y = " << x * y << endl; // 7 * 3 = 21
cout << "x / y = " << x / y << endl; // 整数除法结果为 2
cout << "x % y = " << x % y << endl; // 7 除以 3 的余数是 1
return 0;
}比较运算
比较运算符用于判断两个值之间的关系,常见的有:
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
cout << (a == b) << endl; // 判断 a 是否等于 b,结果是 0(假)
cout << (a != b) << endl; // 判断 a 是否不等于 b,结果是 1(真)
cout << (a < b) << endl; // 判断 a 是否小于 b,结果是 1(真)
return 0;
}逻辑运算
逻辑运算符用于组合多个条件判断,常用的有:
#include <iostream>
using namespace std;
int main() {
int x = 10, y = 20;
cout << ((x < 15) && (y > 10)) << endl; // 判断 x 小于 15 且 y 大于 10
cout << ((x > 15) || (y > 10)) << endl
return 0;
}分支,循环结构
语句
if 语句是最基础的分支结构,允许你根据条件判断是否执行某段代码。只要条件表达式的结果为 true,就会执行相应的代码块。
语法:
if (条件) {
// 条件为 true 时执行的代码
}例:
#include <iostream>
using namespace std;
int main() {
int x = 10;
if (x > 5) { // 判断 x 是否大于 5
cout << "x 大于 5" << endl;
}
return 0;
}语句
if-else 语句是对 if 语句的扩展,提供了当条件不成立时执行的备用代码块。即条件为 true 时执行 if 块中的代码,条件为 false 时执行 else 块中的代码。
语法:
if (条件) {
// 条件为 true 执行的代码
} else {
// 条件为 false 执行的代码
}例:
#include <iostream>
using namespace std;
int main() {
int x = 3;
if (x > 5) {
cout << "x 大于 5" << endl;
} else {
cout << "x 小于或等于 5" << endl;
}
return 0;
}语句
当有多个条件需要判断时,可以使用多个 else if 来判断不同的条件。如果前面的条件都不成立,最终会执行 else 部分的代码。
语法:
if (条件1) {
// 条件1为 true 执行的代码
} else if (条件2) {
// 条件2为 true 执行的代码
} else {
// 所有条件都不为 true 执行的代码
}例:
#include <iostream>
using namespace std;
int main() {
int x = 7;
if (x > 10) {
cout << "x 大于 10" << endl;
} else if (x == 7) {
cout << "x 等于 7" << endl;
} else {
cout << "x 小于 7" << endl;
}
return 0;
}语句
switch 语句用于多条件选择。(没坐 这段没了。。)
语法:
switch (表达式) {
case 常量1:
// 如果表达式值为常量1,执行的代码
break;
case 常量2:
// 如果表达式值为常量2,执行的代码
break;
default:
// 如果表达式值不匹配任何 case,执行的代码
break;
}例:
#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "今天是星期一" << endl;
break;
case 2:
cout << "今天是星期二" << endl;
break;
case 3:
cout << "今天是星期三" << endl;
break;
default:
cout << "无效的输入" << endl;
break;
}
return 0;
}循环结构
循环
for 循环通常用于已知循环次数的情况。它包含三个部分:初始化、条件判断和更新。每次执行时,会按照指定的方式更新循环变量,直到条件不再满足。
语法:
for (初始化; 条件; 更新) {
// 循环体
}例:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << "数字: " << i << endl;
}
return 0;
}循环
while 循环适用于循环次数不确定的情况。它会在每次循环前检查条件,如果条件为 true,则继续执行循环体。
语法:
while (条件) {
// 循环体
}例:
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << "数字: " << i << endl;
i++; // 更新控制变量
}
return 0;
}循环
do-while 循环与 while 循环的不同之处在于,do-while 循环会先执行一次循环体,再进行条件判断。即使条件一开始就不满足,do-while 也会确保循环体至少执行一次。
语法:
do {
// 循环体
} while (条件);例:
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << "数字: " << i << endl;
i++; // 更新控制变量
} while (i <= 5);
return 0;
}&
break就是跳出循环,continue是跳过这次循环,下次正常执行。
#include <iostream>
using namespace std;
int main() {
// break 示例
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // 当 i 等于 3 时跳出循环
}
cout << "数字: " << i << endl;
}
// continue 示例
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // 当 i 等于 3 时跳过当前循环
}
cout << "数字: " << i << endl;
}
return 0;
}数组
数组是一种用于存储多个相同类型数据的容器。你可以把它看成是一个“盒子”,这个盒子里可以装很多相同类型的东西。
定义一个数组的基本语法:
类型 数组名[元素个数];举个例子,如果你想定义一个可以存储 个整数的数组,代码如下:
int arr[10]; // 这是一个可以存储10个整数的数组这里的 arr 就是数组名, 是数组的大小,也就是说你可以在 arr 数组中存储 个整数。
在定义数组时,你也可以选择直接初始化数组的元素。比如:
int arr[5] = {1, 2, 3, 4, 5};这行代码定义了一个包含 个整数的数组,并且将每个元素依次赋值为 。如果没有初始化,数组中的元素会被赋予默认值(对于局部变量,通常是垃圾值)。
你可以通过数组名和索引来访问数组中的每一个元素。在 C++ 中,数组的索引从 开始。例如:
#include <iostream>
using namespace std;
int main() {
int arr[5] = {1, 2, 3, 4, 5};
cout << "第一个元素: " << arr[0] << endl; // 输出 1
cout << "第三个元素: " << arr[2] << endl; // 输出 3
return 0;
}在上面的例子中,我们通过索引来访问数组中的元素,arr[0]是数组中的第一个元素,arr[2]是第三个元素。
多维数组
多维数组是数组的扩展,它可以存储多个数组。
二维数组(最常见)可以看作是一个“数组的数组”。你可以把它想象成一个表格,表格有行和列,每个位置上都可以存放一个数据。
二维数组的定义方式:
类型 数组名[行数][列数];举个例子,假设你要定义一个可以存储3行4列整数的二维数组,代码如下:
int arr[3][4]; // 3行4列的二维数组这时候,arr 是一个二维数组,其中有 行 列,共 个元素。
二维数组的初始化:
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};这个二维数组包含 行 列,分别初始化为:第一行是 ,第二行是 。
访问:
#include <iostream>
using namespace std;
int main() {
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
cout << "第一行第二列的元素: " << arr[0][1] << endl; // 输出 2
cout << "第二行第三列的元素: " << arr[1][2] << endl; // 输出 6
return 0;
}其他维度(doge)
除了二维数组,你还可以定义更多维的数组,例如三维数组、四维数组等。这些数组的定义方式类似,只是维度更多而已。
例如,三维数组的定义方式是:
类型 数组名[维度1][维度2][维度3];int arr[2][3][4]; // 2个二维数组,每个二维数组有3行4列这里的三维数组包含 个二维数组,每个二维数组有 行 列。
当然还有动态数组,不过俺解释不清楚指针,就不写了。。。
字符串
C 风格字符串
定义:
char str[] = "Hello, World!";在这里,str 是一个字符数组,存储了字符串 "Hello, World!"。
访问和操作:
#include <iostream>
using namespace std;
int main() {
char str[] = "Hello, World!";
cout << "第一个字符: " << str[0] << endl; // 输出 H
cout << "第五个字符: " << str[4] << endl; // 输出 o
return 0;
}此外,你可以使用标准库函数对 C 风格字符串进行操作,例如 strlen、strcpy、strcat 等。
#include <iostream>
#include <cstring> // 用于处理C风格字符串
using namespace std;
int main() {
char str1[20] = "Hello";
char str2[] = "World";
// 连接两个字符串
strcat(str1, str2);
cout << "连接后的字符串: " << str1 << endl; // 输出 HelloWorld
// 获取字符串长度
cout << "字符串长度: " << strlen(str1) << endl; // 输出 10
return 0;
}相比于 C 风格字符串,C++ 的string提供了更强大、灵活和安全的字符串处理功能。(会 才是真理)
string类的定义:
#include <iostream>
#include <string> // 包含string类的头文件
using namespace std;
int main() {
string str = "Hello, World!";
cout << str << endl; // 输出 Hello, World!
return 0;
}string类的常见操作:
string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2; // 使用 + 运算符连接字符串
cout << result << endl; // 输出 Hello World
string str = "Hello, World!";
cout << "字符串长度: " << str.size() << endl; // 输出 13可以使用下标运算符来访问字符串中的单个字符:
string str = "Hello";
cout << "第一个字符: " << str[0] << endl; // 输出 H
cout << "最后一个字符: " << str[str.size() - 1] << endl; // 输出 o可以通过赋值的方式修改字符串中的字符:
string str = "Hello";
str[0] = 'h'; // 修改第一个字符
cout << str << endl; // 输出 hellostring类提供了substr()方法来截取字符串的一部分:
string str = "Hello, World!";
string subStr = str.substr(7, 5); // 从第7个字符开始,截取5个字符
cout << subStr << endl; // 输出 World使用find()方法可以查找一个子字符串是否存在,并返回其位置:
string str = "Hello, World!";
size_t pos = str.find("World");
if (pos != string::npos) {
cout << "'World' 在字符串中的位置: " << pos << endl; // 输出 7
} else {
cout << "未找到子字符串" << endl;
}可以使用erase()方法删除字符串的一部分:
string str = "Hello, World!";
str.erase(5, 7); // 从第5个字符开始,删除7个字符
cout << str << endl; // 输出 Hello使用replace()方法可以替换字符串中的部分内容:
string str = "Hello, World!";
str.replace(7, 5, "C++"); // 从第7个字符开始,替换5个字符为"C++"
cout << str << endl; // 输出 Hello, C++!string与C风格字符串的转换
C++ 中的string类与 C 风格字符串之间可以互相转换:
string str = "Hello, World!";
const char* cstr = str.c_str(); // 转换为C风格字符串
cout << cstr << endl; // 输出 Hello, World!
const char* cstr = "Hello, World!";
string str = cstr; // 转换为string类型
cout << str << endl; // 输出 Hello, World!函数
函数是一个可以执行特定任务的代码块。函数通常用于封装一些重复的操作,使得程序结构更清晰,且易于管理和维护。
基本语法结构:
返回类型 函数名(参数类型 参数名1, 参数类型 参数名2, ...) {
// 函数体
// 执行任务的代码
return 返回值; // 如果返回类型是非void,需要返回值
}示例:一个简单的加法函数
#include <iostream>
using namespace std;
// 定义一个函数,返回两个整数之和
int add(int a, int b) {
int sum = a + b; // 计算和
return sum; // 返回结果
}
int main() {
int result = add(5, 3); // 调用add函数
cout << "5 + 3 = " << result << endl; // 输出结果
return 0;
}函数的参数
传值调用
在 C++ 中,函数的参数默认是通过传值的方式传递的。这意味着,在函数内部修改参数的值不会影响函数外部的变量值。
例:
#include <iostream>
using namespace std;
// 传值调用函数,计算传入数字的平方
void square(int num) {
num = num * num; // 修改num的值
cout << "Squared value: " << num << endl;
}
int main() {
int x = 5;
square(x); // 传递x给函数
cout << "Original value of x: " << x << endl; // x没有改变
return 0;
}在这个例子中,虽然我们在square函数内部修改了num的值,但它不会影响main函数中x的值。
传引用调用
如果你希望在函数内部修改传入的参数,并且这些修改能够反映到函数外部,那么你可以使用引用传递。通过引用传递,函数内的参数实际上是原始变量的别名,任何对它的修改都会直接影响到原始变量。
#include <iostream>
using namespace std;
// 传引用调用函数,修改传入的数字
void squareByReference(int &num) {
num = num * num; // 直接修改num的值
}
int main() {
int x = 5;
squareByReference(x); // 传递x的引用
cout << "Squared value of x: " << x << endl; // x被修改为25
return 0;
}在这个例子中,squareByReference函数通过引用修改了x的值,结果在main函数中也能看到x的变化。
(作者并不想写这么长的变量名 奈何俺想装x)
传指针调用(指针后面讲)
除了传值和传引用之外,我们还可以通过指针传递参数。在函数内部,你可以通过指针直接修改参数指向的内存地址中的值。
#include <iostream>
using namespace std;
// 传指针调用函数,修改指针指向的值
void squareByPointer(int *num) {
*num = *num * *num; // 修改指针指向的值
}
int main() {
int x = 5;
squareByPointer(&x); // 传递x的地址
cout << "Squared value of x: " << x << endl; // x被修改为25
return 0;
}通过指针传递,我们也能够修改原始变量的值。&x表示传递x的地址,而*num表示访问指针num指向的内存中的值。
函数的重载
C++支持函数重载,这意味着你可以定义多个同名的函数,只要它们的参数列表不同即可。编译器根据传递给函数的参数类型或个数来决定调用哪个版本的函数。
示例:
#include <iostream>
using namespace std;
// 计算两个整数的和
int add(int a, int b) {
return a + b;
}
// 计算两个浮点数的和
float add(float a, float b) {
return a + b;
}
int main() {
int intSum = add(5, 3); // 调用整数加法
float floatSum = add(5.5f, 3.3f); // 调用浮点数加法
cout << "Integer sum: " << intSum << endl;
cout << "Float sum: " << floatSum << endl;
return 0;
}函数的递归调用
示例:计算阶乘
阶乘是一个常见的递归问题,定义为:
#include <iostream>
using namespace std;
// 递归函数,计算n的阶乘
int factorial(int n) {
if (n == 0) {
return 1; // 递归终止条件
}
return n * factorial(n - 1); // 递归调用
}
int main() {
int n = 5;
cout << "Factorial of " << n << " is " << factorial(n) << endl;
return 0;
}函数的作用域和生命周期
函数的作用域指的是变量可以访问的范围。函数内部声明的变量具有局部作用域,它们只在函数内部有效,函数外部无法访问。而函数外部声明的变量则具有全局作用域,可以在整个程序中访问。
示例:局部变量和全局变量
#include <iostrea>
using namespace std;
int globalVar = 10; // 全局变量
void myFunction() {
int localVar = 5; // 局部变量
cout << "Local variable: " << localVar << endl;
cout << "Global variable: " << globalVar << endl;
}
int main() {
myFunction(); // 调用函数
return 0;
}结构体,类
结构体
结构体(struct) 是一种用户自定义的数据类型,可以将不同类型的变量组合在一起。每个变量叫做结构体的成员,可以是不同数据类型的组合。结构体允许你将多个数据项作为一个单元进行处理,方便存储和操作。
结构体的定义与声明
struct 结构体名 {
数据类型 成员名1;
数据类型 成员名2;
数据类型 成员名3;
// ...
};示例:定义一个简单的结构体
#include <iostream>
using namespace std;
// 定义一个表示学生的结构体
struct Student {
string name; // 姓名
int age; // 年龄
float grade; // 成绩
};
int main() {
// 创建一个Student类型的变量
Student student1;
// 为结构体成员赋值
student1.name = "Tom";
student1.age = 20;
student1.grade = 85.5;
// 输出结构体成员
cout << "Name: " << student1.name << endl;
cout << "Age: " << student1.age << endl;
cout << "Grade: " << student1.grade << endl;
return 0;
}初始化:
#include <iostream>
using namespace std;
// 定义一个结构体
struct Point {
int x;
int y;
};
int main() {
// 通过初始化列表直接初始化结构体变量
Point p1 = {10, 20};
cout << "x: " << p1.x << ", y: " << p1.y << endl;
return 0;
}使用指定初始化:
#include <iostream>
using namespace std;
// 定义一个结构体
struct Point {
int x;
int y;
};
int main() {
// 使用指定初始化
Point p1 = {.x = 10, .y = 20};
cout << "x: " << p1.x << ", y: " << p1.y << endl;
return 0;
}示例:未初始化的结构体
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
float grade;
};
int main() {
Student student1; // 没有初始化
cout << "Name: " << student1.name << endl; // 未定义,可能为垃圾值
cout << "Age: " << student1.age << endl; // 未定义,可能为垃圾值
cout << "Grade: " << student1.grade << endl; // 未定义,可能为垃圾值
return 0;
}结构体的传递
传值调用:
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
float grade;
};
void printStudent(Student student) {
// 修改副本
student.name = "Changed Name";
cout << "Student Name: " << student.name << endl;
}
int main() {
Student student1 = {"Tom", 20, 85.5};
printStudent(student1); // 传递副本
cout << "Original Name: " << student1.name << endl; // 原始结构体未改变
return 0;
}传引用调用:
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
float grade;
};
void updateStudent(Student &student) {
student.name = "Updated Name"; // 修改原始结构体
}
int main() {
Student student1 = {"Tom", 20, 85.5};
updateStudent(student1); // 传递引用
cout << "Updated Name: " << student1.name << endl; // 原始结构体已改变
return 0;
}传指针调用:
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
float grade;
};
void updateStudent(Student *student) {
student->name = "Updated by Pointer"; // 使用指针修改
}
int main() {
Student student1 = {"Tom", 20, 85.5};
updateStudent(&student1); // 传递指针
cout << "Updated Name: " << student1.name << endl; // 原始结构体已改变
return 0;
}结构体数组
C++ 中可以定义结构体数组,这样可以存储多个相同类型的结构体。结构体数组可以用来表示同类事物的集合,比如多个学生的信息。
示例:学生信息数组
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
float grade;
};
int main() {
// 创建一个包含3个学生的结构体数组
Student students[3] = {
{"Tom", 20, 85.5},
{"Alice", 22, 90.0},
{"Bob", 19, 88.5}
};
// 输出所有学生信息
for (int i = 0; i < 3; i++) {
cout << "Name: " << students[i].name << ", Age: " << students[i].age
<< ", Grade: " << students[i].grade << endl;
}
return 0;
}结构体与指针:
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
float grade;
};
int main() {
// 动态创建一个结构体
Student *studentPtr = new Student;
// 通过指针访问和修改结构体成员
studentPtr->name = "Tom";
studentPtr->age = 20;
studentPtr->grade = 85.5;
cout << "Name: " << studentPtr->name << endl;
cout << "Age: " << studentPtr->age << endl;
cout << "Grade: " << studentPtr->grade << endl;
// 删除动态分配的内存
delete studentPtr;
return 0;
}类的定义与使用
类的基本结构:
class 类名 {
public:
// 数据成员
数据类型 成员名1;
数据类型 成员名2;
// 构造函数
类名();
// 成员函数
void 成员函数1();
void 成员函数2();
};示例:定义一个简单的Person类
#include <iostream>
using namespace std;
class Person {
public:
// 数据成员
string name;
int age;
// 构造函数
Person(string n, int a) {
name = n;
age = a;
}
// 成员函数
void introduce() {
cout << "Hello, my name is " << name << " and I am " << age << " years old." << endl;
}
};
int main() {
// 创建对象并初始化
Person person1("Alice", 30);
person1.introduce();
return 0;
}构造函数与析构函数
示例:构造函数
#include <iostream>
using namespace std;
class Rectangle {
public:
int length;
int width;
// 默认构造函数
Rectangle() {
length = 5;
width = 3;
}
// 带参数构造函数
Rectangle(int l, int w) {
length = l;
width = w;
}
void displayArea() {
cout << "Area: " << length * width << endl;
}
};
int main() {
Rectangle rect1; // 调用默认构造函数
Rectangle rect2(10, 6); // 调用带参数构造函数
rect1.displayArea(); // 输出面积:15
rect2.displayArea(); // 输出面积:60
return 0;
}析构函数:
析构函数是类的一种特殊成员函数,用于在对象生命周期结束时进行资源清理。析构函数的名称与类名相同,但前面加一个波浪号~,没有参数,也没有返回值。C++ 会在对象销毁时自动调用析构函数。
class MyClass {
public:
MyClass() {
cout << "Constructor called" << endl;
}
~MyClass() {
cout << "Destructor called" << endl;
}
};
int main() {
MyClass obj; // 创建对象时调用构造函数
return 0; // 程序结束时,调用析构函数
}类的成员函数
类的成员函数定义了类的行为,成员函数可以访问和修改类的成员变量。
成员函数的定义与调用:
#include <iostream>
using namespace std;
class Circle {
private:
float radius;
public:
// 构造函数
Circle(float r) {
radius = r;
}
// 成员函数
float getArea() {
return 3.14 * radius * radius;
}
void setRadius(float r) {
radius = r;
}
};
int main() {
Circle circle1(5); // 创建对象并初始化半径
cout << "Area: " << circle1.getArea() << endl; // 调用成员函数
circle1.setRadius(10); // 设置新的半径
cout << "Updated Area: " << circle1.getArea() << endl; // 调用成员函数
return 0;
}常成员函数:
常成员函数(const成员函数)是指不会修改类成员变量的成员函数。常成员函数的声明中使用const关键字。
class Student {
private:
string name;
public:
Student(string n) : name(n) {}
// 常成员函数
void printName() const {
cout << "Name: " << name << endl;
}
};访问控制:public、private、protected:(后面内容看着玩就行)
class Account {
private:
double balance;
public:
Account(double initial_balance) {
balance = initial_balance;
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
double getBalance() const {
return balance;
}
};
int main() {
Account acc(1000);
acc.deposit(500);
acc.withdraw(200);
cout << "Account balance: " << acc.getBalance() << endl; // 1300
return 0;
}类的继承与多态
继承:
继承是面向对象的一个重要特性,它允许我们在已有的类基础上创建新的类,新的类称为派生类(derived class),继承自基类(base class)的属性和方法。
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
}
};
int main() {
Dog dog;
dog.eat(); // 从Animal继承的成员
dog.bark(); // Dog类自己的成员
return 0;
}多态:
多态是指相同的操作作用于不同的对象时,产生不同的结果。它通常通过虚函数实现。虚函数允许派生类重写基类中的方法,从而在运行时动态决定调用哪个函数。
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle" << endl;
}
};
int main() {
Shape* shape = new Circle();
shape->draw(); // 输出:Drawing a
circle delete shape;
return 0;
}