本文对比了 C 与 C++ 在基本框架、头文件、输入输出、数据类型、强弱类型、const 修饰、三元运算符、引用、函数参数、重载、命名空间、结构体、字符串处理、swap 函数、运算符重载及排序函数等方面的区别。重点介绍了 C++ 中引用的使用、const 常量的特性以及 string 类的基本操作,适合有 C 语言基础的初学者入门。
intadd(int a, int b){ return a + b; }
doubleadd(double a, double b){ return a + b; }
intmain(){
int a, b;
cin >> a >> b;
int x = add(a, b);
double c, d;
cin >> c >> d;
double y = add(c, d);
return0;
}
C++ 里面 namespace 的应用
避免名字冲突。
#include<iostream>usingnamespace std;
namespace A {
int x = 10;
voidfunc1();
}
voidA::func1(){
cout << "hello" << ' ';
}
namespace B {
int x = 20;
voidfunc2();
}
voidB::func2(){
cout << "winter vocation" << endl;
}
intmain(){
cout << A::x << ' ' << B::x << endl;
A::func1();
B::func2();
return0;
}
结构体定义的区别
#include<iostream>#include<string>usingnamespace std;
structStudent {
string name;
int age;
int score[3];
voidsetName(string name1){ name = name1; }
voidsetAge(int age1){ age = age1; }
voidoutput(){
cout << "name: " << name << endl;
cout << "age: " << age << endl;
}
voidsetScore(int score1[3]){
for (int i = 0; i < 3; i++) {
score[i] = score1[i];
}
}
voidoutputScore(){
cout << "chushiscore: ";
for (int i = 0; i < 3; i++) {
cout << score[i] << ' ';
}
cout << endl;
}
voidpaixu(){
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2 - i; j++) {
if (score[j] > score[j + 1]) {
int temp = score[j];
score[j] = score[j + 1];
score[j + 1] = temp;
}
}
}
for (int i = 0; i < 3; i++) {
cout << score[i] << ' ';
}
}
};
intmain(){
Student st;
st.setName("zhangsan");
st.setAge(18);
st.output();
int arr[3] = {90, 80, 70};
st.setScore(arr);
st.outputScore();
st.paixu();
return0;
}
C++ 可以将函数定义在结构体里面,初始化一般都用函数来实现,定义变量的时候可以不加 struct。
string 字符串及其相关函数
string 创建字符串,末尾没有'/0'结尾
string s("hello world");
string s1("nihao");
s = s1; // 可以直接进行复制