C++二级考试核心知识点【内附操作题真题及解析】
声明:例题均来源于网络,仅供学习参考,若涉侵权请联系删除。
以下例题均来自题库:cpp.code2ji.cn
1. C++基础语法
C++对C的扩展
#include <iostream>
#include <string>
using namespace std;int main() {// C++输入输出string name;int age;cout << "请输入姓名: ";cin >> name;cout << "请输入年龄: ";cin >> age;cout << "您好 " << name << ",您今年 " << age << " 岁" << endl;return 0;
}
数据类型
基本数据类型 (继承自C语言):
int
,float
,double
,char
,bool
C++新增类型:
string
: 字符串类bool
: 布尔类型 (true/false)
引用 (Reference)
#include <iostream>
using namespace std;// 值传递
void swap1(int a, int b) {int temp = a;a = b;b = temp;
}// 引用传递
void swap2(int &a, int &b) {int temp = a;a = b;b = temp;
}int main() {int x = 10, y = 20;cout << "交换前: x=" << x << ", y=" << y << endl;swap1(x, y); // 值传递,不会改变原值cout << "值传递后: x=" << x << ", y=" << y << endl;swap2(x, y); // 引用传递,会改变原值cout << "引用传递后: x=" << x << ", y=" << y << endl;return 0;
}
2. 面向对象编程
类的定义和使用
#include <iostream>
#include <string>
using namespace std;class Student {
private:string name;int age;double score;public:// 构造函数Student() {name = "";age = 0;score = 0.0;}Student(string n, int a, double s) {name = n;age = a;score = s;}// 析构函数~Student() {cout << name << " 对象被销毁" << endl;}// 设置器 (Setter)void setName(string n) { name = n; }void setAge(int a) { age = a; }void setScore(double s) { score = s; }// 获取器 (Getter)string getName() const { return name; }int getAge() const { return age; }double getScore() const { return score; }// 成员函数void display() const {cout << "姓名: " << name << ", 年龄: " << age << ", 成绩: " << score << endl;}// 判断是否及格bool isPassed() const {return score >= 60;}
};int main() {// 创建对象Student s1; // 调用默认构造函数Student s2("张三", 20, 85.5); // 调用带参构造函数// 使用对象s1.setName("李四");s1.setAge(19);s1.setScore(92.0);s1.display();s2.display();if (s2.isPassed()) {cout << s2.getName() << " 及格了!" << endl;}return 0;
}
继承
#include <iostream>
#include <string>
using namespace std;// 基类
class Person {
protected:string name;int age;public:Person(string n, int a) : name(n), age(a) {}virtual void display() const {cout << "姓名: " << name << ", 年龄: " << age << endl;}virtual ~Person() {} // 虚析构函数
};// 派生类
class Student : public Person {
private:string studentId;double score;public:Student(string n, int a, string id, double s) : Person(n, a), studentId(id), score(s) {}// 重写父类方法void display() const override {Person::display(); // 调用父类方法cout << "学号: " << studentId << ", 成绩: " << score << endl;}bool isPassed() const {return score >= 60;}
};class Teacher : public Person {
private:string subject;double salary;public:Teacher(string n, int a, string sub, double sal) : Person(n, a), subject(sub), salary(sal) {}void display() const override {Person::display();cout << "学科: " << subject << ", 工资: " << salary << endl;}
};int main() {Student s("张三", 20, "2021001", 85.5);Teacher t("李老师", 35, "数学", 8000);s.display();cout << "是否及格: " << (s.isPassed() ? "是" : "否") << endl;cout << endl;t.display();return 0;
}
3. 运算符重载
#include <iostream>
using namespace std;class Complex {
private:double real, imag;public:Complex(double r = 0, double i = 0) : real(r), imag(i) {}// 重载 + 运算符Complex operator+(const Complex& other) const {return Complex(real + other.real, imag + other.imag);}// 重载 - 运算符Complex operator-(const Complex& other) const {return Complex(real - other.real, imag - other.imag);}// 重载 << 运算符 (友元函数)friend ostream& operator<<(ostream& os, const Complex& c) {os << c.real;if (c.imag >= 0) os << "+";os << c.imag << "i";return os;}// 重载 >> 运算符 (友元函数)friend istream& operator>>(istream& is, Complex& c) {cout << "请输入实部和虚部: ";is >> c.real >> c.imag;return is;}
};int main() {Complex c1(3, 4);Complex c2(1, 2);Complex c3 = c1 + c2;Complex c4 = c1 - c2;cout << "c1 = " << c1 << endl;cout << "c2 = " << c2 << endl;cout << "c1 + c2 = " << c3 << endl;cout << "c1 - c2 = " << c4 << endl;Complex c5;cin >> c5;cout << "您输入的复数是: " << c5 << endl;return 0;
}
4. 模板 (Templates)
函数模板
#include <iostream>
using namespace std;// 函数模板
template <typename T>
T maximum(T a, T b) {return (a > b) ? a : b;
}// 模板特化
template <>
const char* maximum<const char*>(const char* a, const char* b) {return (strcmp(a, b) > 0) ? a : b;
}int main() {cout << "最大整数: " << maximum(10, 20) << endl;cout << "最大浮点数: " << maximum(3.14, 2.71) << endl;cout << "较大字符: " << maximum('A', 'Z') << endl;return 0;
}
类模板
#include <iostream>
using namespace std;template <typename T>
class Stack {
private:T* arr;int top;int capacity;public:Stack(int size = 10) {capacity = size;arr = new T[capacity];top = -1;}~Stack() {delete[] arr;}void push(T item) {if (top < capacity - 1) {arr[++top] = item;} else {cout << "栈已满!" << endl;}}T pop() {if (top >= 0) {return arr[top--];} else {cout << "栈为空!" << endl;return T();}}bool isEmpty() const {return top == -1;}int size() const {return top + 1;}
};int main() {Stack<int> intStack(5);Stack<string> stringStack(3);// 整数栈intStack.push(10);intStack.push(20);intStack.push(30);cout << "整数栈大小: " << intStack.size() << endl;while (!intStack.isEmpty()) {cout << intStack.pop() << " ";}cout << endl;// 字符串栈stringStack.push("Hello");stringStack.push("World");stringStack.push("C++");cout << "字符串栈大小: " << stringStack.size() << endl;while (!stringStack.isEmpty()) {cout << stringStack.pop() << " ";}cout << endl;return 0;
}
5. STL (标准模板库)
Vector
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;int main() {vector<int> numbers;// 添加元素numbers.push_back(3);numbers.push_back(1);numbers.push_back(4);numbers.push_back(1);numbers.push_back(5);// 遍历cout << "原始数据: ";for (int num : numbers) {cout << num << " ";}cout << endl;// 排序sort(numbers.begin(), numbers.end());cout << "排序后: ";for (int num : numbers) {cout << num << " ";}cout << endl;// 查找auto it = find(numbers.begin(), numbers.end(), 4);if (it != numbers.end()) {cout << "找到4,位置: " << (it - numbers.begin()) << endl;}return 0;
}
Map
#include <iostream>
#include <map>
#include <string>
using namespace std;int main() {map<string, int> scores;// 插入数据scores["张三"] = 85;scores["李四"] = 92;scores["王五"] = 78;// 访问数据cout << "张三的成绩: " << scores["张三"] << endl;// 遍历mapcout << "所有学生成绩:" << endl;for (auto& pair : scores) {cout << pair.first << ": " << pair.second << endl;}// 查找if (scores.find("李四") != scores.end()) {cout << "找到李四的成绩" << endl;}return 0;
}
6. 异常处理
#include <iostream>
#include <stdexcept>
using namespace std;class DivisionByZeroException : public exception {
public:const char* what() const noexcept override {return "除数不能为零!";}
};double divide(double a, double b) {if (b == 0) {throw DivisionByZeroException();}return a / b;
}int main() {try {double result1 = divide(10, 2);cout << "10 / 2 = " << result1 << endl;double result2 = divide(10, 0); // 会抛出异常cout << "10 / 0 = " << result2 << endl;} catch (const DivisionByZeroException& e) {cout << "捕获到自定义异常: " << e.what() << endl;} catch (const exception& e) {cout << "捕获到标准异常: " << e.what() << endl;}cout << "程序继续执行..." << endl;return 0;
}
7. 考试重点提醒
- C++语法扩展: cin/cout、引用、bool类型、string类
- 面向对象: 类的定义、构造/析构函数、继承、多态
- 运算符重载: 算术运算符、输入输出运算符重载
- 模板: 函数模板、类模板的基本使用
- STL容器: vector、map、set的基本操作
- 异常处理: try-catch-throw语句的使用
- 内存管理: new/delete操作符的使用
8. 常见编程题型
- 类设计: 根据要求设计类,实现属性和方法
- 继承应用: 基类派生类设计,虚函数使用
- 运算符重载: 为自定义类重载运算符
- 模板应用: 设计通用的函数或类模板
- STL应用: 使用容器解决实际问题
- 算法实现: 排序、查找、数据处理
- 异常处理: 程序健壮性设计
9. 编程规范
- 命名规范: 类名大驼峰,函数名小驼峰
- 头文件包含: 只包含必要的头文件
- 内存管理: new和delete要配对使用
- 异常安全: 适当使用异常处理机制
- 代码组织: 合理分离声明和定义
- 注释: 复杂逻辑要有清晰注释
当然可以!以下是按照你要求整理成 Markdown 笔记格式 的 C++ 题目详解,每题都标明了来源、题目描述、示例输出、修改处和详细解析,适合作为学习资料或复习笔记使用。
C++ 操作题真题部分
该例题来自题库:cpp.code2ji.cn
🎼 乐章修复记:交响乐类定义与使用
✅ 题目描述:
程序定义了一个名为 Symphony
的类,用于表示交响乐作品。每个对象包含标题、作者和乐章数量。修复程序,使其正确输出两首交响乐的信息。
🔸 示例输出:
贝多芬的c小调第五交响乐.命运有4个乐章
莫扎特的g小调第四十交响乐有4个乐章
🛠️ 错误修复点(标注 // ERROR **********found**********
):
// 原错误:void ~Symphony();
// 正确修改:
~Symphony();
// 原错误:char author[];
// 正确修改:
char *author;
// 原错误:Symphony::Symphony(char *str1, char *str2,int count=4)
// 正确修改:
Symphony::Symphony(char *str1, char *str2,int count):movement(count)
✅ 正确运行代码:
#include <iostream>
#include <cstring>
#pragma warning (disable:4996)
using namespace std;class Symphony {
public:Symphony(char *str1, char *str2, int count = 4);~Symphony();void Display() const;
private:char *title;char *author;const int movement;
};Symphony::Symphony(char *str1, char *str2, int count): movement(count) {title = new char[strlen(str1) + 1];strcpy(title, str1);author = new char[strlen(str2) + 1]; strcpy(author, str2);
}Symphony::~Symphony() {delete[] title;delete[] author;
}void Symphony::Display() const {cout << author << "的" << title << "有" << movement << "个乐章" << endl;
}int main() {Symphony s1("c小调第五交响乐.命运", "贝多芬", 4);Symphony s2("g小调第四十交响乐", "莫扎特", 4);s1.Display();s2.Display();return 0;
}
📘 解析:
- 析构函数不能有
void
前缀。 author
是动态字符数组,应为char*
而不是char[]
。movement
是const
类型,必须在构造函数初始化列表中赋值。- 使用
new char[strlen(...)+1]
和strcpy
来分配和复制字符串。
📛 姓名输出:继承与构造函数的调用
该例题来自题库:cpp.code2ji.cn
✅ 题目描述:
类 Surname
用于存储姓氏,类 Name
继承 Surname
,用于输出全名,要求格式为:姓在前,名在后。
🔸 示例输出:
zhang yu
🛠️ 错误修复点:
// 错误:SetSurname(s);
// 正确:
surname = s;
// 错误:Name(string s, string n) : ______
// 正确:
Name(string s, string n) : Surname(s)
// 错误:Print 调用
Surname::Print();
// 错误:main函数调用
onePerson.Print();
✅ 正确代码:
#include <iostream>
#include <string>
using namespace std;class Surname {
public:Surname(string s) {SetSurname(s);}void SetSurname(string s) {surname = s;}void Print() const {cout << surname << " ";}
protected:string surname;
};class Name : public Surname {
public:Name(string s, string n) : Surname(s) {SetName(n);}void SetName(string n) {name = n;}void Print() const {Surname::Print();cout << name << endl;}
private:string name;
};int main() {Name onePerson("zhang", "yu");onePerson.Print();return 0;
}
📘 解析:
- 构造函数中调用父类构造函数必须通过初始化列表实现。
- 父类方法可通过
类名::方法名()
调用。 - 成员变量
surname
和name
组合输出姓名。
🧮 七进制数列:进制转换类设计
该例题来自题库:cpp.code2ji.cn
✅ 题目描述:
类 Septinary
用于将十进制整数转换为七进制数,并输出字符串形式。
🔸 示例输出:
246
129 的七进制表示为:
2*49 + 4*7 + 6 = 246
🛠️ 修复 createSeptinary
函数:
void Septinary::createSeptinary(int num) {char temp[100];int index = 0;while (num > 0) {temp[index++] = numberToChar(num % 7);num /= 7;}// 倒序存储for (int i = 0; i < index; ++i) {data[i] = temp[index - i - 1];}data[index] = '\0';
}
✅ 完整代码结构:
#include <iostream>
using namespace std;class Septinary {
public:Septinary(int num);~Septinary();void show();
private:char* data;void createSeptinary(int num);char numberToChar(int num);
};Septinary::Septinary(int num) {data = new char[100];createSeptinary(num);
}Septinary::~Septinary() {if (data != NULL)delete[] data;
}void Septinary::createSeptinary(int num) {char temp[100];int index = 0;while (num > 0) {temp[index++] = numberToChar(num % 7);num /= 7;}for (int i = 0; i < index; ++i)data[i] = temp[index - i - 1];data[index] = '\0';
}char Septinary::numberToChar(int num) {if (num < 0 || num > 6) {cout << "error number" << endl;return '0';}return char(num + '0');
}void Septinary::show() {cout << data << endl;
}int main() {Septinary s(129);s.show();return 0;
}
📘 解析:
- 使用
%7
和/7
循环将十进制转七进制。 - 存入临时数组需倒序输出。
- 使用
numberToChar()
转换为 ASCII 字符。
⏰ 时钟修正:12小时制打印
该例题来自题库:cpp.code2ji.cn
✅ 题目描述:
类 CClock
表示一个时钟对象,要求将时间以 12 小时制
方式打印(附 AM/PM)。
🔸 示例输出:
Clock 1: 0:00 AM
Clock 2: 9:00 AM
Clock 3: 3:45 PM
🛠️ 错误修复点:
- 构造函数初始化错误:
// 错误:hour = hour;
// 正确:
this->hour = hour;
- 打印函数除法错误:
// 错误:hour / 12
// 正确:hour % 12
✅ 正确代码片段:
class CClock {
public:CClock() : hour(0), minute(0) {}CClock(int hour) {this->hour = hour;minute = 0;}CClock(int hour, int minute) : hour(hour), minute(minute) {}void PrintUsing12() const {int h = hour % 12;if (h == 0) h = 12;cout << h << ":" << (minute < 10 ? "0" : "") << minute;cout << (hour < 12 ? " AM" : " PM") << endl;}
private:int hour;int minute;
};int main() {CClock clock1;CClock clock2(9);CClock clock3(15, 45);cout << "Clock 1: ";clock1.PrintUsing12();cout << "Clock 2: ";clock2.PrintUsing12();cout << "Clock 3: ";clock3.PrintUsing12();return 0;
}
📘 解析:
- 使用
%12
得到 12 小时制小时数。 - 注意
0
点应显示为12
。 - AM/PM 判定基于
hour
是否小于 12。
附题库链接:全网最全的C++题库