龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

C++中关键字Struct和Class的区别(3)

时间:2014-10-01 02:20来源:网络整理 作者:网络 点击:
分享到:
复制代码 代码如下: /* ** FileName : StructAndClassDiffDemo ** Author : Jelly Young ** Date : 2013/12/7 ** Description : More information, please go to http://www.jb51.net */ #include iostream

复制代码 代码如下:

/*
** FileName     : StructAndClassDiffDemo
** Author       : Jelly Young
** Date         : 2013/12/7
** Description  : More information, please go to http://www.jb51.net
*/
 
#include <iostream>
using namespace std;
 
struct A
{
private:
    int b;
 
protected:
    int c;
 
public:
    A()
    {
        b = 10;
        c = 20;
        d = 30;
    }
 
    int d;
};
 
struct B : A
{
    void printA_C()
    {
        cout<<A::c<<endl;
    };
 
    // private member can not see
    /*void printA_B()
    {
    cout<<A::b<<endl;
    }*/
 
    void printA_D()
    {
        cout<<A::d<<endl;
    }
};
 
int main(int argc, char* argv[])
{
 
    A a1;
    B b1;
 
    // private member can not see
    //cout<<a1.b<<endl;
 
    // protected member can not see
    //cout<<a1.c<<endl;
 
    // public member can see
    cout<<a1.d<<endl;
 
    return 0;
}

写了这么多了,那么会出现这种一个状况,如果是class的父类是struct关键字描述的,那么默认访问属性是什么?

当出现这种情况时,到底默认是public继承还是private继承,取决于子类而不是基类。class可以继承自struct修饰的类;同时,struct也可以继承自class修饰的类,继承属性如下列描述:

复制代码 代码如下:

class B:A{}; // private 继承
 
class A{};
struct B:A{}; // public 继承

最后,那么到底是使用struct,还是使用class呢?这个看个人喜好,但是这里有一个编程规范的问题,当你觉得你要做的更像是一种数据结构的话,那么用struct,如果你要做的更像是一种对象的话,那么用class。

精彩图集

赞助商链接