C++类class和结构体struct区别

   C++语言继承了 C语言的 struct,并且加以扩充。在 C语言中,struct 是只能定义数据成员,而不能定义成员函数的。而在 C++ 中,struct 类似于 class,既可以定义数据成员,又可以定义成员函数。

   在 C++ 中,struct 与 class 基本是通用的,唯一不同的是如果使用 class 关键字,类中定义的成员变量或成员函数默认都是 private 属性的,而采用 struct 关键字,结构体中定义的成员变量或成员函数默认都是 public 属性的。

   在 C++ 中,没有抛弃 C语言中的 struct 关键字,其意义就在于给 C 语言程序开发人员有一个归属感,并且能让 C++ 编译器兼容以前用 C 语言开发出来的项目。

#include<iostream>
using namespace std;
struct book
{
    double price;
    char * title;
    void display();
};
void book::display()
{
    cout<<title<<", price: "<<price<<endl;
}
int main()
{
    book Alice;
    Alice.price = 29.9;     //It’s OK
    Alice.title = "Alice in wonderland";  //It’s OK
    Alice.display();        //It’s OK
    return 0;
}
posted @ 2022-08-19 22:48  luoganttcc  阅读(18)  评论(0)    收藏  举报