1. hellowrold
#include <iostream>
using namespace std;//使用标准命名空间
int main() {
cout << "Hello World!" << endl;
return 0;
}
makefile
all:
g++ main.cpp -o app
2. 计算圆的面积
#include <iostream>
#define PI 3.14
using namespace std;//使用标准命名空间
class Mycircle{
private:
double r;
double s;
public:
void setR(double r){
this->r = r;
}
double gets(){
return PI*r*r;
}
};
int main() {
Mycircle c1;
c1.setR(4);
cout << "半径为4的圆的面积为:" << c1.gets() << endl;
return 0;
}
makefile
all:
g++ main.cpp -o app
3. 指针传递与值传递的区别
#include <iostream>
using namespace std;//使用标准命名空间
//通过指针进行值交换
void swap_1(int *a,int *b ){
int c;
c = *b;
*b = *a;
*a = c;
}
void swap_2(int x,int y ){
int z;
z = x;
y = x;
x = z;
}
int main() {
int a = 10;
int b = 20;
int x = 10;
int y = 20;
swap_1(&a,&b);
cout << "a的值:" << a << endl;
cout << "b的值:" << b << endl;
swap_2(x,y);
cout << "x的值:" << x << endl;
cout << "y的值:" << y << endl;
return 0;
}
makefile
all:
g++ main.cpp -o app
执行结果:
通俗的来说,值传递只是把变量的值当做参数传递进子函数中,无论函数体中如何改变参数值,主函数的变量值都不会改变。
而地址传递,是把变量的地址传入子函数中,子函数中对于参数的改变,是通过传入的地址参数去内存中修改该变量存储的值,所以主函数中的变量值也会同步改变
4. 数组
#include <iostream>
#include <stdio.h>
using namespace std;//使用标准命名空间
int main() {
int i;
int arr_1[] = {2,4,5,1,3};//初始化
//访问数组
for (i=0;i<5;i++){
printf("arr_1[%d] = %d\n",i,arr_1[i]);
}
return 0;
}
makefile
all:
g++ main.cpp -o app
执行结果:
5. 字符串
#include <iostream>
#include <stdio.h>
using namespace std;//使用标准命名空间
int main() {
char str_1[6] = {'H','e','l','l','o','\0'};
//字符串实际上是使用 null 字符 \0 终止的一维字符数组
//由于在数组的末尾存储了空字符,所以字符数组的大小比单词 Hello 的字符数多一个
cout << str_1 << endl;
//依据数组初始化规则,您可以把上面的语句写成以下语句:
char str_2[] = "Hello";
cout << str_2 << endl;
return 0;
}
执行结果: