Home >Backend Development >C++ >C++ and C++: What's the difference?
The difference between C vs. C: Type system: C is weaker, C is stronger and requires explicit conversion. Objects and classes: Not supported by C, supported by C, allowing the creation and use of custom types. Inheritance and polymorphism: Not supported by C, supported by C, allowing class inheritance and reuse features. Function and operator overloading: Not supported by C, supported by C, allowing custom function and operator behavior.
C vs. C: Nuance Analysis
Foreword
C Yes An object-oriented programming language derived from the C language. Despite the similarities, there are important differences between the two languages. This article explores these differences and provides code examples to deepen understanding.
Type system
// C int a = 10; double b = a; // 隐式转换 // C++ int a = 10; double b = static_cast<double>(a); // 显式转换
Objects and Classes
// C++ class Person { public: string name; }; Person john; // 创建一个 Person 对象 cout << john.name; // 访问对象的成员
Inheritance and polymorphism
// C++ class Employee : public Person { public: int salary; }; Employee mary; // 创建一个 Employee 对象 cout << mary.name << ", " << mary.salary; // 访问对象属性和方法
Function overloading and operator overloading
// C++ int add(int a, int b); // 函数重载 double operator+(double a, double b); // 运算符重载
Practical case
Consider a program that calculates the average:
C
#include <stdio.h> int main() { int num1, num2; printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); float avg = (num1 + num2) / 2.0; printf("Average: %.2f\n", avg); }
C
#include <iostream> using namespace std; int main() { int num1, num2; cout << "Enter two numbers: "; cin >> num1 >> num2; double avg = static_cast<double>(num1 + num2) / 2; cout << "Average: " << fixed << setprecision(2) << avg << endl; }
In the C version, explicit type conversion is used to ensure that avg
is of type double
for accurate averaging value. Additionally, cout
and cin
are used for input and output, enhancing the user interface.
The above is the detailed content of C++ and C++: What's the difference?. For more information, please follow other related articles on the PHP Chinese website!