基本使用
常量
常量是固定值,在程序执行期间不会改变。这些固定的值,又叫做字面量。常量可以是任何的基本数据类型,可分为整型数字、浮点数字、字符、字符串和布尔值。常量就像是常规的变量,只不过常量的值在定义后不能进行修改。
//1.整数常量
a1=212 // 合法的
a2=215u // 合法的
a3=0xFeeL // 合法的
//2.浮点常量
a4=3.14159 // 合法的
a5=314159E-5L // 合法的
//3.布尔常量
a6=true //值代表真
a7=false //值代表假
//4.字符常量
cout<<"\\,\b"<<endl;//转义字符
//5.字符串常量
//字符串字面值或常量是括在双引号 "" 中的。一个字符串包含类似于字符常量的字符:普通的字符、转义序列和通用的字符。您可以使用 \ 做分隔符,把一个很长的字符串常量进行分行。
//6.定义常量
//使用 #define 预处理器。使用 const 关键字。
#define identifier value
const type variable = value;
修饰符类型
//C++ 允许在 char、int 和 double 数据类型前放置修饰符。
//修饰符 signed、unsigned、long 和 short 可应用于整型,signed 和 unsigned 可应用于字符型,long 可应用于双精度型。修饰符 signed 和 unsigned 也可以作为 long 或 short 修饰符的前缀。例如:unsigned long int。
函数
每个 C++ 程序都至少有一个函数,即主函数 main()
函数声明告诉编译器函数的名称、返回类型和参数。函数定义提供了函数的实际主体。
C++ 标准库提供了大量的程序可以调用的内置函数。例如,函数 strcat() 用来连接两个字符串,函数 memcpy() 用来复制内存到另一个位置。
//函数基本形式:
return_type function_name( parameter list )
{
body of the function
}
//返回类型:一个函数可以返回一个值。return_type 是函数返回的值的数据类型。有些函数执行所需的操作而不返回值,在这种情况下,return_type 是关键字 void。
//函数名称:这是函数的实际名称。函数名和参数列表一起构成了函数签名。
//参数:参数就像是占位符。当函数被调用时,您向参数传递一个值,这个值被称为实际参数。参数列表包括函数参数的类型、顺序、数量。参数是可选的,也就是说,函数可能不包含参数。
//函数主体:函数主体包含一组定义函数执行任务的语句。
//函数参数传递方式:1.传值调用2.指针调用3.引用调用
数组
type arrayName [ arraySize ];
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
字符串
C++ 提供了以下两种类型的字符串表示形式:
1.C 风格字符串
2.C++ 引入的 string 类类型
char site[7] = {'R', 'U', 'N', 'O', 'O', 'B', '\0'};
char site[] = "RUNOOB";//c类型风格
strcpy(s1, s2);//复制字符串 s2 到字符串 s1。
strcat(s1, s2);//连接字符串 s2 到字符串 s1 的末尾。连接字符串也可以用 + 号
strlen(s1);//返回字符串 s1 的长度。
strcmp(s1, s2);//如果 s1 和 s2 是相同的,则返回 0;如果 s1<s2 则返回值小于 0;如果 s1>s2 则返回值大于 0。
strchr(s1, ch);//返回一个指针,指向字符串 s1 中字符 ch 的第一次出现的位置。
strstr(s1, s2);//返回一个指针,指向字符串 s1 中字符串 s2 的第一次出现的位置。
string str1 = "runoob";
string str2 = "google";//c++类型风格
str3 = str1 + str2;
len = str3.size();
指针
面向对象
#include <iostream>
using namespace std;
class Box
{
public:
double length; // 长度
double breadth; // 宽度
double height; // 高度
// 成员函数声明
double get(void);
void set( double len, double bre, double hei );
};
// 成员函数定义
double Box::get(void)
{
return length * breadth * height;
}
void Box::set( double len, double bre, double hei)
{
length = len;
breadth = bre;
height = hei;
}
int main( )
{
Box Box1; // 声明 Box1,类型为 Box
Box Box2; // 声明 Box2,类型为 Box
Box Box3; // 声明 Box3,类型为 Box
double volume = 0.0; // 用于存储体积
// box 1 详述
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 详述
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// box 1 的体积
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Box1 的体积:" << volume <<endl;
// box 2 的体积
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Box2 的体积:" << volume <<endl;
// box 3 详述
Box3.set(16.0, 8.0, 12.0);
volume = Box3.get();
cout << "Box3 的体积:" << volume <<endl;
return 0;
}