C++ 代码例子

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;
}

执行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值