#include2.c++中字符串数组的应用#include using namespace std; int main() { srand(time(0)); int array[10]; for (int i = 0; i < 10; i++) { array[i] = rand() % 50 + 1; } for (int i = 0; i < 10; i++) { cout << array[i] << " "; } cout << endl; for (int i = 0; i < 10 - 1; i++) { for (int j = 0; j < 10 - 1 - i; j++) { if (array[j] > array[j + 1]) { int temp = array[j + 1]; array[j + 1] = array[j]; array[j] = temp; } } } for (int i = 0; i < 10; i++) { cout << array[i] << " "; } return 0; }
#include#include using namespace std; int main() { string name[3] = { "张三","李四","王五" }; for (int i = 0; i < 3; i++) { cout << name[i] << endl; } return 0; }
呜呜呜,c++还能直接创建字符串数组太喜欢了,c语言根本没法这样做。
3.c++函数的分文件编写 1.创建.h后缀名的头文件创建就行
2.创建.cpp后缀名的源文件创建就行
3.在头文件中写函数的声明#pragma once #include4.在源文件中写函数的定义using namespace std; void swap(int a, int b);
#include "swap.h"//利用这个和头文件关联起来
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}
5.在写项目的文件中应用
#include "swap.h"//包含那个自己创建的头文件," "代表自己写的 #include4.c++指针 1.const修饰指针 ————常量指针using namespace std; int main() { int a = 10; int b = 20; swap(a, b);//直接传 return 0; }
1.不能对指针指向的值做修改
#includeusing namespace std; int main() { int a = 10; int b = 20; const int* p = &a; *p = 10;//错误的,vs直接报红,我们不能这样做 return 0; }
2.能改变指针的指向
#include2.const修饰常量 ————指针常量using namespace std; int main() { int a = 10; int b = 20; const int* p = &a; p = &b;//这样我们是允许的 return 0; }
1.能对指针指向的值做修改
#includeusing namespace std; int main() { int a = 10; int b = 20; int* const p = &a; *p = 20;//可以这样做 return 0; }
2.不能对指针指向做修改
#include3.const既修饰指针,又修饰常量using namespace std; int main() { int a = 10; int b = 20; int* const p = &a; p = &b;//这样是错误的 return 0; }
1.指针指向的值不能修改
#includeusing namespace std; int main() { int a = 10; int b = 20; const int* const p = &a; *p = 10;//这样不对 return 0; }
2.指针指向的地址不能修改
#include5.c++结构体 1.结构体的定义和使用using namespace std; int main() { int a = 10; int b = 20; const int* const p = &a; p = &b;//我们也不允许这样操作 return 0; }
在c++中,定义结构体时要struct关键字,但当使用它时,可以不带上关键字,这点比c语言方便多了
#include6.在c++中还可以这样使用字符串#include #include using namespace std; struct Student { string name; int age; double score; }; int main() { Student s1;//我们可以直接用名字在c++中 s1.name = "张三"; s1.age = 20; s1.score = 100; cout << "姓名:" << s1.name << "年龄:" << s1.age << "成绩:" << fixed << setprecision(2) << s1.score << endl; return 0; }
#include#include using namespace std; struct Teacher { int data; string name; }; int main() { Teacher teacher[3]; string fuzhi = "ABC";//像一个字符数组一样 for (int i = 0; i <3; i++) { teacher[i].data = i; teacher[i].name = "teacher_"; teacher[i].name += fuzhi[i];//竟然可以直接加上 } for (int i = 0; i < 3; i++) { cout << teacher[i].data <<" "; cout << teacher[i].name << endl; } }



