example
example

C/C++ C++语法

Yann

站长
管理成员
GTAOS管理组
认证卖家
认证用户
本 月 名 人 榜 最 佳
1. 基本数据类型和变量声明:

C++:
int age = 25;
double pi = 3.14159;
char grade = 'A';
bool isTrue = true;


2. 控制流语句:
- if-else语句:

C++:
if (age >= 18) {
    cout << "You are an adult." << endl;
} else {
    cout << "You are a minor." << endl;
}

- for循环:

C++:
for (int i = 0; i < 5; i++) {
    cout << "Value of i: " << i << endl;
}

- while循环:

C++:
int i = 0;
while (i < 5) {
    cout << "Value of i: " << i << endl;
    i++;
}

- do-while循环:

C++:
int i = 0;
do {
    cout << "Value of i: " << i << endl;
    i++;
} while (i < 5);

- switch语句:

C++:
int day = 2;
switch (day) {
    case 1:
        cout << "Monday" << endl;
        break;
    case 2:
        cout << "Tuesday" << endl;
        break;
    default:
        cout << "Invalid day" << endl;
}

3. 数组和指针:
C++:
int numbers[5] = {1, 2, 3, 4, 5};
int* ptr = numbers;
cout << "First element: " << *ptr << endl;

4. 函数和参数传递:

C++:
int add(int a, int b) {
    return a + b;
}

int result = add(3, 4);
cout << "Result: " << result << endl;

5. 类和对象:

C++:
class Rectangle {
private:
    int length;
    int width;

public:
    Rectangle(int l, int w) {
        length = l;
        width = w;
    }

    int calculateArea() {
        return length * width;
    }
};

Rectangle rect(4, 5);
int area = rect.calculateArea();
cout << "Area: " << area << endl;

进阶:

6. 指针:

C++:
int number = 10;
int* ptr = &number; // 声明一个整型指针并将其指向number变量的地址
cout << "Value of number: " << *ptr << endl; // 通过指针访问number的值


7. 引用:

C++:
int number = 10;
int& ref = number; // 声明一个整型引用并将其绑定到number变量
cout << "Value of number: " << ref << endl; // 通过引用访问number的值

8. 继承:

C++:
class Animal {
public:
    void sound() {
        cout << "Animal makes a sound" << endl;
    }
};


class Dog : public Animal {
public:
    void sound() {
        cout << "Dog barks" << endl;
    }
};


Dog dog;
dog.sound(); // 输出 "Dog barks"


9 多态:

C++:
class Animal {
public:
    virtual void sound() {
        cout << "Animal makes a sound" << endl;
    }
};


class Dog : public Animal {
public:
    void sound() {
        cout << "Dog barks" << endl;
    }
};


Animal* animal = new Dog();
animal->sound(); // 输出 "Dog barks"


10. 模板:

C++:
template<typename T>
T add(T a, T b) {
    return a + b;
}


int sum = add(3, 4); // 使用模板函数进行整数相加
double total = add(2.5, 3.7); // 使用模板函数进行浮点数相加
 
最后编辑:
顶部