在 C 语言中声明结构体变量时需要加上 struct 关键字.而在 C++ 中可以不加 struct 关键字进行结构体变量的声明。并且允许使用函数。

C 语言风格:

#include <stdio.h>
struct student{
    char *name[1];
    int age;
    int score;
};

int main(){
    struct student xiaoMing;
    xiaoMing.name[0] = "小明";
    xiaoMing.age = 20;
    xiaoMing.score = 90;
    printf("姓名:%s\n",xiaoMing.name[0]);
    printf("年龄:%d\n",xiaoMing.age);
    printf("分数:%d\n",xiaoMing.score);
    return 0;
}

C++ 风格:

#include <iostream>
#include <string.h>
using namespace std;
struct student{
    string name;
    int age;
    int score;

};
int main(){
    student xiaoMing;
    xiaoMing.name = "小明";
    xiaoMing.age = 20;
    xiaoMing.score = 90;
    cout << "姓名:" << xiaoMing.name <<endl;
    cout << "年龄:" << xiaoMing.age <<endl;
    cout << "分数:" << xiaoMing.score <<endl;
    return 0;
}

相同结果:

姓名:小明
年龄:20
分数:90

C++ 中允许结构体内定义函数

#include <iostream>

using namespace std;
struct Student
{
    string name;
    void setName(string name){
        this->name = name;
    }
};

int main(){
    Student s1;
    s1.name = "陈杰海";
    s1.setName("陈陈菌");
    cout << s1.name << endl;
    return 0;
}

运行结果:

陈陈菌
文章目录