从C语言过渡到c++,肯定要掌握这些吧
1.面向对象编程:
- C语言是过程化编程语言,它主要关注函数和过程。
- C++支持面向对象编程,提供类、继承、多态等特性。
// C++中的类和对象
class Rectangle {
private:
int width, height;
public:
Rectangle(int w, int h) : width(w), height(h) {}
int area() { return width * height; }
};
int main() {
Rectangle rect(3, 4);
cout << "Area: " << rect.area() << endl;
return 0;
}
2.封装和访问控制:
- C语言没有类的概念,因此没有访问控制。
- C++支持封装和访问控制,可以使用public、private和protected关键字控制成员的访问权限。
// C++中的封装和访问控制
class BankAccount {
private:
double balance;
public:
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount acc;
acc.deposit(1000);
cout << "Balance: " << acc.getBalance() << endl;
return 0;
}
3.函数重载:
- C语言不支持函数重载。
- C++支持函数重载,允许定义多个同名函数,只要它们的参数列表不同即可。
// C++中的函数重载
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
4.动态内存管理:
- C语言使用malloc()和free()进行动态内存分配和释放。
- C++引入了new和delete运算符,用于动态内存的分配和释放,同时提供了RAII(资源获取即初始化)的概念。
// C++中的动态内存管理
int* arr = new int[10]; // 分配动态数组
delete[] arr; // 释放动态数组
5.默认参数:
- C语言不支持默认参数。
- C++支持默认参数,可以在函数声明中给参数一个默认值,调用函数时可以不传递这个参数。
// C++中的默认参数
void printMessage(string message = "Hello") {
cout << message << endl;
}
int main() {
printMessage(); // 输出默认消息
printMessage("Bonjour"); // 输出指定消息
return 0;
}
6.模板编程:
- C语言不支持模板编程。
- C++支持模板编程,可以编写泛型代码,使得算法在不同类型数据上都能工作。
// C++中的模板编程
template<typename T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << "Sum of integers: " << add(5, 3) << endl;
cout << "Sum of doubles: " << add(3.5, 2.5) << endl;
return 0;
}
7.异常处理:
- C语言通过返回值或者全局变量来处理错误。
- C++支持异常处理机制,使用try、catch、throw关键字来捕获和处理异常。
// C++中的异常处理
int divide(int a, int b) {
if (b == 0) {
throw "Division by zero!";
}
return a / b;
}
int main() {
try {
cout << "Result: " << divide(10, 0) << endl;
} catch (const char* msg) {
cout << "Error: " << msg << endl;
}
return 0;
}
8.命名空间:
- C语言没有命名空间的概念,所有的函数和变量都在全局命名空间中。
- C++支持命名空间,可以将一组相关的函数、类、变量等放在一个命名空间中,避免命名冲突。
// C++中的命名空间
namespace Math {
const double PI = 3.14159265;
double square(double x) {
return x * x;
}
}
int main() {
cout << "PI: " << Math::PI << endl;
cout << "Square of 5: " << Math::square(5) << endl;
return 0;
}
9. 引用:
- C语言没有引用的概念,只能通过指针来实现类似的功能。
- C++支持引用,引用提供了一个对象的别名,通常用于函数参数传递和返回值。
10.运算符重载:
- C语言不支持运算符重载。
- C++支持运算符重载,可以重新定义运算符的行为,使其适用于自定义类型。
// C++中的运算符重载
class Complex {
private:
double real, imag;
public:
Complex(double r, double i) : real(r), imag(i) {}
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex a(2, 3);
Complex b(4, 5);
Complex c = a + b;
c.display();
return 0;
}