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

转自:http://www.weixueyuan.net/view/6337.html

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

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

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

[例1] C++ struct 示例:

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

在本例中,定义了一个名为book的struct,在其中定义有成员变量title和price,此外还声明了一个函数,该函数在struct内部声明,在结构体外部定义。

程序看到这里,不难发现,struct和class关键字在C++中其基本语法是完全一样的。接着,我们来看一下主函数。首先通过book结构体定义了一个对象Alice。通过成员选择符,Alice对象在接下来的三行代码中分别调用了book结构体中定义的变量及函数!

由此可见struct声明中,默认的属性为public属性,在struct外部可以随意访问。

[例2] C++ class 示例:

#include<iostream>
using namespace std;

class book
{
    double price;
    char * title;
    void display();
};

void book::display()
{
    cout<<title<<", price: "<<price<<endl;
}

int main()
{
    book Alice;
    Alice.price = 29.9;     //compile error
    Alice.title = "Alice in wonderland";  // compile error
    Alice.display();        // compile error
    return 0;
}

再来看例2,例2程序相对于例1,只改动了一处:将struct关键字替换为class关键字。结果,在主函数中定义Alice对象之后,我们再企图通过Alice对象访问其内部的price、title变量及display函数,此时编译器便会提示编译错误,错误提示为这三者是不可访问的。

正如我们所预料的那样,确实class中定义的成员变量或成员函数,默认的属性是private。

例3:

class book
{
public:
    void setprice(double a);
    double getprice();
private:
    double price;
};

例4:

struct book
{
    void setprice(double a);
    double getprice();
private:
    double price;
};

例5:

struct book
{
public:
    void setprice(double a);
    double getprice();
private:
    double price;
};

在前面小节中,我们定义了如例3所示的一个名为book的类,而与其相等价的struct定义则可以如例4所示,如果我们显式的在struct中将setprice和getprice成员函数声明为public属性,这也是可以的,如例5所示。 

posted @ 2018-02-19 14:50  shuziluoji  阅读(113)  评论(0编辑  收藏  举报