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

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

时间:2014-10-01 02:20来源:网络整理 作者:网络 点击:
分享到:
再让我写代码验证一下: 复制代码 代码如下: /* ** FileName : StructAndClassDiffDemo ** Author : Jelly Young ** Date : 2013/12/7 ** Description : More information, please go to http://

再让我写代码验证一下:

复制代码 代码如下:

/*
** 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
{
    int a;
    A()
    {
        a = 10;
    }
    void print()
    {
        cout<<"I am from A"<<endl;
    }
};
 
struct B : A
{
    int b;
    B()
    {
        a = 30; // set a to 30
        b = 20;
    }
    /*void print()
    {
    cout<<"I am from B"<<endl;
    }*/
};
 
int main(int argc, char* argv[])
{
    B b1;
    cout<<b1.a<<endl;
    cout<<b1.b<<endl;
    b1.print();
 
    A a1;
    cout<<a1.a<<endl;
    a1.print();
 
    return 0;
}

运行上述代码,struct支持继承。

Struct支持多态么?

写代码测试一下便知:

复制代码 代码如下:

/*
** 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
{
    virtual void print() = 0;
};
 
struct B : A
{
    void print()
    {
        cout<<"I am from B"<<endl;
    }
};
 
struct C : A
{
    void print()
    {
        cout<<"I am from C"<<endl;
    }
};
 
int main(int argc, char* argv[])
{    
    A *a1;    
    B *b1 = new B;    
    C *c1 = new C;    
    a1 = b1;    
    a1->print(); // call B, not A
 
    a1 = c1;
    a1->print(); // call C, not A
 
    return 0;
}

Struct支持Private、Protected和Public关键字么?

精彩图集

赞助商链接