C# 和 C++ 在变量与数据类型方面的主要区别
特性/方面 | C# | C++ | 说明(含举例) |
---|---|---|---|
语言类型 | 现代托管语言,运行在 .NET CLR 上 | 低级、性能强、接近硬件的系统语言 | C# 有垃圾回收,比如创建字符串不用手动释放:string s = "hello"; C++ 需要手动管理内存: char* s = new char[6]; strcpy(s, "hello"); delete[] s; |
变量声明 | 必须声明类型,支持类型推断(var ) | 必须声明类型,C++11 起支持 auto 类型推断 | C# 支持:var x = 10; C++ 支持: auto x = 10; |
数据类型 | 有内置的高级数据类型(string 、decimal ) | 复杂,支持内置类型和自定义类型 | C# 内置字符串类型:string name = "张三"; C++ 需要使用标准库字符串: std::string name = "张三"; |
字符串 | string 是引用类型,内置强大字符串库 | 使用 std::string (标准库)或裸指针 | C# 字符串拼接:string s = "Hello" + " World"; C++ 字符串拼接: std::string s = std::string("Hello") + " World"; |
常量声明 | 使用 const 和 readonly | 使用 const | C# 编译时常量:const double PI = 3.14; 运行时只读字段: readonly double E; C++ 只有编译时常量: const double PI = 3.14; |
类型安全 | 强类型语言,运行时安全检查 | 强类型,但更多底层操作和指针 | C# 不允许隐式转换产生风险:double i = 10; int d = i; 安全C++ 指针操作更灵活但易错,如 int* p = (int*)0x1234; |
类型转换 | 明确区分隐式和显式转换((int) 、Convert ) | 支持强制类型转换((int) 、static_cast ) | C# 强制转换:int i = (int)3.14; ,字符串转整数:int n = int.Parse("123"); C++ 强制转换: int i = static_cast<int>(3.14); ,字符串转整数:int n = stoi("123"); |
自动内存管理 | 有垃圾回收,变量生命周期自动管理 | 需手动管理(new /delete 或智能指针) | C# 变量自动释放:string s = "abc"; C++ 需手动释放: int* p = new int(5); delete p; 或使用智能指针:std::unique_ptr<int> p(new int(5)); |