目录
前言
作为一个C语言开发者,对C++总是有些忌惮——大多数都能看懂,但总被一些语法或函数绕晕,会有“C++代码怎么这样写?”、“反人类(反C语言规则)!”的疑惑与愤怒。
随着时间的流逝,棱角已被磨平,想来终究还是要把C++搞清楚,毕竟工作中总会遇到。学会之后,自然就痛快了。
所以,最近开始自学C++。看书籍、搜网站,发现大多数规则与C语言是一致的;对于其他不一致的部分,打算总结一下,一来加深印象,二来随时复习。于是有了本文。
C++与C的异同
在学习的过程中,发现C++的语法和变量与C语言几乎是一样的(也对,毕竟C++是基于C语言进行扩展的)。相同之处:
数据类型:bool、int、float、double
运算符:算数运算符、复制运算符、比较运算符、逻辑运算符、位运算符。
但也有一些不同,差异之处在于:
输入输出:cin、cout
字符(串):char、string
结构体:声明方式
引用:&运算
当然还有类class
与对象object
的差别,这个后边再讲。
C++与C的差异
头文件
在C++中有许多库,引用时居然可以不加.h
(自己定义的需要加.h)。如:
#include <iostream>
#include <string>
#include <myHeadFile.h> // 我自己定义的头文件
而C语言都需要添加
#include <stdio.h>
#include <myHeadFile.h>
输入/输出
在C语言中,输入和输出接口为scanf
和printf
,比如:
int a, b;
scanf("%d %d", &a, &b); // 输入:4 5
printf("Print: a:%d, b:%d\n", a, b);
// Print:a:4, b:5
在C++中,输入接口为cin
,输出接口为cout
,同时需要添加namespace
或std::
,比如:
#include <iostream> // 头文件库
using namespace std; // 可以使用标准库中的对象和变量的名称
int x;
cin >> x; // 输入x变量的数值,比如50
cout << "print x = " << x << "\n";
// print x = 50
string name;
cin >> name; // 只能输入一个单词,空格为终止符,如输入"Michael Jackson"
cout << "Name is: " << name << "\n"
// Name is: Michael
// 多个单词,getline()获取一行内容
string name;
getline(cin, name); // 输入多个单词,如输入"Michael Jackson"
cout << "Name is: " << name << "\n";
// Name is: Michael Jackson
若省略命名空间(Omitting Namespace)
,即不声明using namespace std
,也可以使用std::
来调用接口,如
#include <iostream>
std::string x;
std::cin >> x; // 输入Michael
std::cout << "Print: " << x << "\n";
// Print: Michael
字符串类型
在各种变量类型中,C++与C差别最大的就是字符(串)
了。
字符串声明
在C语言中,字符类型char
可声明字符、字符串
,比如
char c = 'a'; // 字符
char str[] = "Hello"; // 字符串组
char *str = "World"; //字符串
在C++中,char
只能声明字符
或字符串数组
,字符串
只能用string
来声明,且需要包含头文件#include <string>
,比如:
#include <string>
char c = 'a';
char str[] = "Hello";
string str = "World";
字符串长度
在C++中,string
声明的字符串是个object(对象)
,可以调用一系列方法,比如:
int l, s;
string str = "hello world";
l = str.length(); // str的长度
s = str.size(); // 同上
字符串连接
在C语言中,+
运算符只能进行数字计算。
在C++中,+
运算符可以在字符串之间使用,将它们连接在一起成为新的字符串,称为串联(Concatenation)
(C语言不能这么做),如:
string firstName = "Michael";
string LastName = "Jackson";
string fullName = firstName + LastName;
cout << "Print: " << fullName;
// Print: Michael Jackson
cout << "Print: " << firstName + LastName;
// Print: Michael Jackson
由于string是个对象类型,其中包含可以对字符串执行某些操作的函数,例如可以使用append()
方法将字符串连接。
string fullName = firstName.append(lastName);
cout << "Print: " << fullName;
// Print: Michael Jackson
NOTE
:x.append(y)
会把y连接在x之后,且中间加个空格" "
等同于x + " " + y
。
字符串数组
C语言中,字符串数组相当于二级指针
,可以用以下方式声明:
char *str[2] = {"Hello", "Wrold"};
C++中,string本身就是字符串,字符串数组声明如下:
string str[2] = {"Hello", "World"};
可以将string
理解成C语言中的一级指针(char *)类型
,一切都打通了。
多维数组
C++中的3维字符串数组
,其实相当于C语言中的4维数组
。
string letters[2][3][4] = {
{
{"a", "b", "c", "d"},
{"e", "f", "g", "h"},
{"i", "j", "k", "l"}
},
{
{"0", "1", "2", "3"},
{"4", "5", "6", "7"},
{"8", "9", "10", "11"}
}
};
多维数组非常擅长表示网格。如下使用一个多维数组
来表示一个战舰小游戏
:
// 摘自 w3schools C++ Tutorial
#include <iostream>
using namespace std;
int main() {
// We put "1" to indicate there is a ship.
bool ships[4][4] = {
{ 0, 1, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 }
};
// Keep track of how many hits the player has and how many turns they have played in these variables
int hits = 0;
int numberOfTurns = 0;
// Allow the player to keep going until they have hit all four ships
while (hits < 4) {
int row, column;
cout << "Selecting coordinates\n";
// Ask the player for a row
cout << "Choose a row number between 0 and 3: ";
cin >> row;
// Ask the player for a column
cout << "Choose a column number between 0 and 3: ";
cin >> column;
// Check if a ship exists in those coordinates
if (ships[row][column]) {
// If the player hit a ship, remove it by setting the value to zero.
ships[row][column] = 0;
// Increase the hit counter
hits++;
// Tell the player that they have hit a ship and how many ships are left
cout << "Hit! " << (4-hits) << " left.\n\n";
} else {
// Tell the player that they missed
cout << "Miss\n\n";
}
// Count how many turns the player has taken
numberOfTurns++;
}
cout << "Victory!\n";
cout << "You won in " << numberOfTurns << " turns";
return 0;
}
结构体
C++与C语言声明结构体对比。
// C/C++相同
struct {
string brand;
string model;
int year;
} my_car1, my_car2;
my_car1.brand = "Audi";
my_car1.model = "A4L";
my_car1.year = 2020;
struct car {
string brand;
string model;
int year;
};
// C
struct car my_car1;
struct car my_car2;
my_car1.brand = "Audi";
// C++
// 不需要再加struct
car myCar1;
car myCar2;
myCar1.brand = "Audi";
引用References
引用变量Reference Variable
引用变量
是对现有变量的“引用”,使用&运算符
创建引用变量。
例如,使用&
创建tool
,用来引用变量car
:
string car = "Audi";
string &tool = car; // 把现有变量car引用为新变量tool
cout << car << "\n";
cout << tool << "\n";
// Audi
// Audi
内存地址Memory Address
在 C++ 中创建变量时,会为该变量分配一个内存地址。而当我们给变量赋值时,它就存储在这个内存地址中。
要想知道这个地址,需要使用&运算符
,结果表示变量的存储位置
:
string car = "Audi";
cout << "Memory Address: " << &car;
// Memory Address: 0x6dfed4
指针
&
:Reference operator
引用运算符,计算结果为地址
;
*
:Dereference operator
解除引用运算符,计算结果为指针(地址)内的内容
。
string car = "Audi";
string* carAddr = &car;
cout << "Print: " << car << " and " << &car << " and " << carAddr;
// Print: Audi and 0x6dfed4 and 0x6dfed4
cout << "Print: " << *carAddr;
// Print: Audi