首页 百科知识 ++类和结构体区别

++类和结构体区别

时间:2022-09-22 百科知识 版权反馈
【摘要】:[例1] C++ struct 示例:#includeusing namespace std;struct book{ double price; char * title; void display();};void book::display(){ cout<


[例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。

免责声明:以上内容源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。

我要反馈