c++面试基础知识点
持续更新
1、 c++ struct和class有什么区别?
答案
在C++里,`struct`和`class`主要区别在于默认访问权限: - `struct`默认成员和继承权限是`public`。 - `class`默认成员和继承权限是`private`。其他方面,二者语法和功能基本一致。
- struct:可以和C语言的
struct
保持较好的兼容性,当你需要编写既可以在C语言中使用,又可以在C++中使用的代码时,使用struct
更合适。 - class:是C++特有的概念,不能直接在C语言中使用。
2、 C++里,const
用途详细介绍并举例
答案
在C++里,const
用途广泛,以下为你详细介绍并举例:
1. 定义常量
- 用途:声明常量,保证其值在初始化后不可修改,提高代码安全性和可读性。
- 示例
const int MAX_SIZE = 100;
// MAX_SIZE = 200; // 编译错误,不能修改常量的值
2. 修饰函数参数
- 用途:表明函数不会修改传入参数的值,避免意外修改,还能接收常量对象。
- 示例
#include <iostream>
void printValue(const int num) {// num = 10; // 编译错误,不能修改const参数std::cout << num << std::endl;
}
int main() {const int a = 5;printValue(a);return 0;
}
3. 修饰成员函数
- 用途:表明该成员函数不会修改对象的成员变量,常被用于读取对象状态的函数。
- 示例
#include <iostream>
class Rectangle {
private:int width, height;
public:Rectangle(int w, int h) : width(w), height(h) {}int getArea() const {// width = 10; // 编译错误,const成员函数不能修改成员变量return width * height;}
};
int main() {const Rectangle rect(3, 4);std::cout << rect.getArea() << std::endl;return 0;
}
4. 修饰指针
- 用途:分为常量指针(指针指向的内容不可变)和指针常量(指针本身不可变),明确指针的使用规则。
- 示例
int num = 10;
// 常量指针:指向的内容不可修改
const int* ptr1 = #
// *ptr1 = 20; // 编译错误,不能通过ptr1修改指向的值
// 指针常量:指针本身不可修改
int* const ptr2 = #
// ptr2 = nullptr; // 编译错误,不能修改ptr2指向的地址
5. 修饰引用
- 用途:保证引用的对象不被修改,常用于函数参数传递,避免复制开销。
- 示例
#include <iostream>
void printRef(const int& ref) {// ref = 10; // 编译错误,不能通过const引用修改对象std::cout << ref << std::endl;
}
int main() {int value = 5;printRef(value);return 0;
}