Skip to content

10. 结构体与联合体

10.1 结构体

10.2 联合体

cpp
#include <iostream>

class Rectangle {
private:
    int length;
    int width;

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

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

int main() {
    Rectangle rect(5, 3);
    int area = rect.calculateArea();

    std::cout << "矩形的面积是: " << area << std::endl;

    return 0;
}

在这个示例中,我们定义了一个名为Rectangle的类,该类具有私有的length和width成员变量,以及公共的构造函数和calculateArea()成员函数。构造函数用于初始化矩形的长度和宽度,而calculateArea()函数用于计算矩形的面积。

在main()函数中,我们创建了一个Rectangle对象rect,并调用它的calculateArea()函数来计算矩形的面积。最后,我们将结果输出到控制台上。

这个示例展示了面向对象编程的一些基本概念,例如类的定义、对象的创建和成员函数的调用。在实际的面向对象编程中,还可以涉及更多的特性,如继承、多态和封装等。

程序基本概念:

cpp
#include <iostream>

int main() {
    // 标识符、常量、变量和表达式
    int num1 = 5;
    int num2 = 10;
    int sum = num1 + num2;

    // 输出结果
    std::cout << "sum = " << sum << std::endl;

    return 0;
}

基本数据类型:

cpp
#include <iostream>

int main() {
    // 整数型
    int num = 10;
    long long bigNum = 10000000000LL;

    // 实数型
    float floatValue = 3.14f;
    double doubleValue = 3.14159;

    // 字符型
    char ch = 'A';

    // 布尔型
    bool isTrue = true;

    return 0;
}

程序基本语句

cpp
#include <iostream>

int main() {
    // 输入语句
    int num;
    std::cout << "请输入一个整数: ";
    std::cin >> num;

    // 输出语句
    std::cout << "您输入的整数是: " << num << std::endl;

    // 赋值语句
    int x = 5;
    int y;
    y = x;

    // 条件语句
    if (x > y) {
        std::cout << "x 大于 y" << std::endl;
    }
    else if (x < y) {
        std::cout << "x 小于 y" << std::endl;
    }
    else {
        std::cout << "x 等于 y" << std::endl;
    }

    // 循环语句
    for (int i = 0; i < 5; i++) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

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

    do {
        std::cout << i << " ";
        i--;
    } while (i > 0);
    std::cout << std::endl;

    return 0;
}