Top 30 C++面试题及答案

概述
以下是Top 30 C++面试题及答案,从基础到高级分类,非常适合工作面试和技术轮次。
🟢 基础级别 (1–10)
1. 什么是C++?
C++是由Bjarne Stroustrup开发的通用、面向对象编程语言。它支持过程式和面向对象编程,使其成为多范式语言。
2. C++的主要特性是什么?
OOP支持(类、继承、多态)
函数和运算符重载
模板
异常处理
STL(标准模板库)
3. C和C++之间有什么区别?
特性
C
C++
范式
过程式
多范式
OOP
函数重载
封装
4. iostream的用途是什么?
#include <iostream>用于C++中使用cincout`进行输入/输出操作。
5. cincout之间有什么区别?
cin用于输入。
cout用于输出。
两者都是iostream库的一部分。
6. C++中的数据类型有哪些?
基本类型:intfloatdoublecharbool
派生类型:arraypointer
用户定义类型:structclassunionenum
7. ===之间有什么区别?
=赋值运算符。
==比较运算符。
8. C++中的指针是什么?
指针是存储另一个变量内存地址的变量。
9. 什么是引用变量?
引用变量是使用&创建的另一个变量的别名
  1. int a = 10;
  2. int &ref = a;
cpp
10. 什么是构造函数?
构造函数是在创建对象时自动调用的特殊函数
🟡 中级级别 (11–20)
11. 什么是函数重载?
函数重载允许具有相同名称不同参数的多个函数。
12. 什么是运算符重载?
运算符重载允许您为运算符定义自定义行为
  1. class A {
  2. int x;
  3. public:
  4. A(int i): x(i) {}
  5. A operator+(A a) { return A(x + a.x); }
  6. };
cpp
13. C++中的继承是什么?
继承是一个类(子类)继承另一个类(父类)属性的过程。
14. 继承的类型有哪些?
单继承
多继承
多级继承
层次继承
混合继承
15. 什么是多态?
多态意味着具有多种形式。它允许相同的函数名对不同的输入表现出不同的行为。
16. 编译时多态和运行时多态之间有什么区别?
编译时:函数重载、运算符重载
运行时:虚函数
17. 什么是虚函数?
虚函数允许运行时多态,使用virtual关键字声明。
18. 什么是纯虚函数?
  1. virtual void show() = 0;
cpp
它使类成为抽象类,派生类必须重写它。
19. 什么是封装?
封装是通过将数据和函数包装到单个单元(类)中来隐藏数据
20. 什么是抽象?
抽象意味着隐藏内部细节,只显示相关信息。
🔴 高级级别 (21–30)
21. 什么是标准模板库(STL)?
STL是通用类和函数的库,如vectormapsetqueue等。
22. 类和结构体之间有什么区别?
特性
结构体
默认访问权限
private
public
OOP支持
部分
23. 什么是访问说明符?
public:在任何地方都可访问
private:仅在类内可访问
protected:在类内和派生类内可访问
24. 构造函数的类型有哪些?
默认构造函数
参数化构造函数
拷贝构造函数
25. 什么是析构函数?
析构函数是使用~ClassName()的特殊函数,用于释放内存
26. newmalloc()之间有什么区别?
new调用构造函数malloc不调用
new是C++;malloc是C
27. 什么是this指针?
它是指向当前对象的指针。
28. C++中的智能指针是什么?
智能指针自动管理内存(shared_ptrunique_ptrweak_ptr)。
29. 什么是异常处理?
使用trycatchthrow处理运行时错误的机制。
30. C++中的模板是什么?
模板允许编写通用代码
  1. template <typename T>
  2. T add(T a, T b) {
  3. return a + b;
  4. }
cpp
详细代码示例
基础概念示例
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;

  4. // 1. 基本数据类型和变量
  5. void basicDataTypes() {
  6. int integer = 10;
  7. float floating = 3.14f;
  8. double doubleNum = 3.14159;
  9. char character = 'A';
  10. bool boolean = true;
  11. cout << "Integer: " << integer << endl;
  12. cout << "Float: " << floating << endl;
  13. cout << "Double: " << doubleNum << endl;
  14. cout << "Char: " << character << endl;
  15. cout << "Bool: " << boolean << endl;
  16. }

  17. // 2. 指针和引用
  18. void pointersAndReferences() {
  19. int x = 10;
  20. int* ptr = &x; // 指针
  21. int& ref = x; // 引用
  22. cout << "Original value: " << x << endl;
  23. cout << "Pointer value: " << *ptr << endl;
  24. cout << "Reference value: " << ref << endl;
  25. // 通过指针修改值
  26. *ptr = 20;
  27. cout << "After pointer modification: " << x << endl;
  28. // 通过引用修改值
  29. ref = 30;
  30. cout << "After reference modification: " << x << endl;
  31. }

  32. // 3. 函数重载
  33. int add(int a, int b) {
  34. return a + b;
  35. }

  36. double add(double a, double b) {
  37. return a + b;
  38. }

  39. string add(string a, string b) {
  40. return a + b;
  41. }
cpp
面向对象编程示例
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;

  4. // 基类
  5. class Animal {
  6. protected:
  7. string name;
  8. int age;
  9. public:
  10. // 构造函数
  11. Animal(string n, int a) : name(n), age(a) {
  12. cout << "Animal constructor called" << endl;
  13. }
  14. // 虚函数
  15. virtual void makeSound() {
  16. cout << "Some animal sound" << endl;
  17. }
  18. // 纯虚函数
  19. virtual void move() = 0;
  20. // 析构函数
  21. virtual ~Animal() {
  22. cout << "Animal destructor called" << endl;
  23. }
  24. };

  25. // 派生类
  26. class Dog : public Animal {
  27. private:
  28. string breed;
  29. public:
  30. // 构造函数
  31. Dog(string n, int a, string b) : Animal(n, a), breed(b) {
  32. cout << "Dog constructor called" << endl;
  33. }
  34. // 重写虚函数
  35. void makeSound() override {
  36. cout << name << " says: Woof!" << endl;
  37. }
  38. // 实现纯虚函数
  39. void move() override {
  40. cout << name << " is running" << endl;
  41. }
  42. // 析构函数
  43. ~Dog() {
  44. cout << "Dog destructor called" << endl;
  45. }
  46. };

  47. // 运算符重载示例
  48. class Complex {
  49. private:
  50. double real, imag;
  51. public:
  52. Complex(double r = 0, double i = 0) : real(r), imag(i) {}
  53. // 运算符重载
  54. Complex operator+(const Complex& c) const {
  55. return Complex(real + c.real, imag + c.imag);
  56. }
  57. Complex operator-(const Complex& c) const {
  58. return Complex(real - c.real, imag - c.imag);
  59. }
  60. // 输出运算符重载
  61. friend ostream& operator<<(ostream& out, const Complex& c) {
  62. out << c.real << " + " << c.imag << "i";
  63. return out;
  64. }
  65. };
cpp
模板和STL示例
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <algorithm>
  6. #include <memory>
  7. using namespace std;

  8. // 函数模板
  9. template<typename T>
  10. T findMax(T a, T b) {
  11. return (a > b) ? a : b;
  12. }

  13. // 类模板
  14. template<typename T>
  15. class Stack {
  16. private:
  17. vector<T> elements;
  18. public:
  19. void push(const T& element) {
  20. elements.push_back(element);
  21. }
  22. T pop() {
  23. if (elements.empty()) {
  24. throw runtime_error("Stack is empty");
  25. }
  26. T element = elements.back();
  27. elements.pop_back();
  28. return element;
  29. }
  30. bool isEmpty() const {
  31. return elements.empty();
  32. }
  33. size_t size() const {
  34. return elements.size();
  35. }
  36. };

  37. // STL容器使用示例
  38. void stlExamples() {
  39. // Vector
  40. vector<int> numbers = {1, 2, 3, 4, 5};
  41. numbers.push_back(6);
  42. // Map
  43. map<string, int> scores;
  44. scores["Alice"] = 95;
  45. scores["Bob"] = 87;
  46. scores["Charlie"] = 92;
  47. // Set
  48. set<int> uniqueNumbers = {1, 2, 2, 3, 3, 4};
  49. // 算法
  50. sort(numbers.begin(), numbers.end());
  51. auto maxElement = max_element(numbers.begin(), numbers.end());
  52. cout << "Max element: " << *maxElement << endl;
  53. }

  54. // 智能指针示例
  55. void smartPointerExamples() {
  56. // unique_ptr
  57. unique_ptr<int> ptr1(new int(10));
  58. cout << "Unique ptr value: " << *ptr1 << endl;
  59. // shared_ptr
  60. shared_ptr<string> ptr2 = make_shared<string>("Hello");
  61. shared_ptr<string> ptr3 = ptr2; // 引用计数增加
  62. cout << "Shared ptr value: " << *ptr2 << endl;
  63. cout << "Reference count: " << ptr2.use_count() << endl;
  64. // weak_ptr
  65. weak_ptr<string> weakPtr = ptr2;
  66. cout << "Weak ptr expired: " << weakPtr.expired() << endl;
  67. }
cpp
异常处理示例
  1. #include <iostream>
  2. #include <stdexcept>
  3. using namespace std;

  4. // 自定义异常类
  5. class DivisionByZeroException : public exception {
  6. public:
  7. const char* what() const noexcept override {
  8. return "Division by zero is not allowed";
  9. }
  10. };

  11. // 异常处理函数
  12. double divide(double a, double b) {
  13. if (b == 0) {
  14. throw DivisionByZeroException();
  15. }
  16. return a / b;
  17. }

  18. // 异常处理示例
  19. void exceptionHandlingExample() {
  20. try {
  21. double result = divide(10, 0);
  22. cout << "Result: " << result << endl;
  23. }
  24. catch (const DivisionByZeroException& e) {
  25. cout << "Caught exception: " << e.what() << endl;
  26. }
  27. catch (const exception& e) {
  28. cout << "Caught general exception: " << e.what() << endl;
  29. }
  30. catch (...) {
  31. cout << "Caught unknown exception" << endl;
  32. }
  33. }

  34. // RAII(资源获取即初始化)示例
  35. class ResourceManager {
  36. private:
  37. int* resource;
  38. public:
  39. ResourceManager() : resource(new int(0)) {
  40. cout << "Resource acquired" << endl;
  41. }
  42. ~ResourceManager() {
  43. delete resource;
  44. cout << "Resource released" << endl;
  45. }
  46. void useResource() {
  47. cout << "Using resource: " << *resource << endl;
  48. }
  49. };
cpp
高级特性示例
  1. #include <iostream>
  2. #include <functional>
  3. #include <thread>
  4. #include <chrono>
  5. using namespace std;

  6. // Lambda表达式示例
  7. void lambdaExamples() {
  8. // 基本lambda
  9. auto add = [](int a, int b) { return a + b; };
  10. cout << "Lambda result: " << add(5, 3) << endl;
  11. // 捕获列表
  12. int multiplier = 10;
  13. auto multiply = [multiplier](int x) { return x * multiplier; };
  14. cout << "Multiply result: " << multiply(5) << endl;
  15. // 可变lambda
  16. int counter = 0;
  17. auto increment = [&counter]() mutable { return ++counter; };
  18. cout << "Counter: " << increment() << endl;
  19. cout << "Counter: " << increment() << endl;
  20. }

  21. // 函数对象示例
  22. class Adder {
  23. private:
  24. int value;
  25. public:
  26. Adder(int v) : value(v) {}
  27. int operator()(int x) const {
  28. return x + value;
  29. }
  30. };

  31. // 移动语义示例
  32. class MoveExample {
  33. private:
  34. int* data;
  35. size_t size;
  36. public:
  37. // 构造函数
  38. MoveExample(size_t s) : size(s) {
  39. data = new int[size];
  40. cout << "Constructor called" << endl;
  41. }
  42. // 拷贝构造函数
  43. MoveExample(const MoveExample& other) : size(other.size) {
  44. data = new int[size];
  45. for (size_t i = 0; i < size; ++i) {
  46. data[i] = other.data[i];
  47. }
  48. cout << "Copy constructor called" << endl;
  49. }
  50. // 移动构造函数
  51. MoveExample(MoveExample&& other) noexcept
  52. : data(other.data), size(other.size) {
  53. other.data = nullptr;
  54. other.size = 0;
  55. cout << "Move constructor called" << endl;
  56. }
  57. // 析构函数
  58. ~MoveExample() {
  59. delete[] data;
  60. cout << "Destructor called" << endl;
  61. }
  62. };
cpp
面试技巧
1. 准备阶段
复习C++基础语法和概念
练习编写面向对象代码
理解内存管理和指针
熟悉STL容器和算法
练习模板编程
2. 面试中
仔细阅读问题要求
先思考再编码
解释你的设计思路
考虑内存安全和性能
讨论代码的可维护性
3. 常见陷阱
忘记处理内存泄漏
忽略const正确性
不熟悉移动语义
缺乏对RAII的理解
忽略异常安全
总结
这30个C++面试题涵盖了从基础概念到高级特性的各个方面:
基础概念:数据类型、指针、引用、函数
面向对象编程:类、继承、多态、封装
高级特性:模板、STL、智能指针、异常处理
现代C++:Lambda表达式、移动语义、RAII
最佳实践:内存管理、性能优化、代码设计
掌握这些概念将帮助您在C++面试中表现出色,并在实际工作中编写高效、安全的代码。