struct和class的区别

本文详细介绍了C++中struct和class的区别,特别是在访问控制上的不同。通过一个具体的继承例子,展示了如何在C++中使用struct来实现继承,并演示了如何在派生类中增加新的成员函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 struct是C语言的概念,在标准C中,标准C中是不允许在结构中声明函数的,而在C++的类中是可以声明函数的。

      但是在C++中struct和class意义一样,唯一不同就是struct里面默认的访问控制是public,class中默认的访问控制是private。在C++中struct中也可以构造函数、析构函数、它们之间也可以继承

      下面的代码演示了struct继承的例子:

#include < iostream.h >
/*******************************************************/
/* 动物基类
/******************************************************
*/

enum  BREED {GOLDEN,CAING,DANDIE,SHETLAND,DOBERMAN,LAB} ;
struct  Animal
{
public:
    Animal():m_nAge(
2),m_nWeight(20){}
    
~Animal(){}
//操作
public:
    
int GetAge() const{return m_nAge;}//get the age of the animal
    void SetAge(int nAge){m_nAge=nAge;}//set the age of the animal
    int GetWeight()const{return m_nWeight;}//get the wight of the animal
    void SetWeight(int nWeight){m_nWeight=nWeight;}//set the weight of the animal
//属性
protected:
    
int m_nAge;
    
int m_nWeight;
}
;
/*******************************************************/
/*
/******************************************************
*/

struct  Cat: public  Animal
{
public:
    Cat():m_Breed(GOLDEN)
{}
    
~Cat(){}
public:
    BREED GetBreed()
    
{
        
return m_Breed;
    }

    
void SetBreed(BREED breed)
    
{
        m_Breed
=breed;
    }

private:
    BREED m_Breed;
}
;
/*******************************************************/
/* 主函数
/******************************************************
*/

int  main()
{
    Cat cat;
    
int nAge;
    
int nWeight;
    BREED breed;
    cat.SetAge(
10);
    cat.SetWeight(
100);
    cat.SetBreed(GOLDEN);

    nAge
=cat.GetAge();
    nWeight
=cat.GetWeight();
    breed
=cat.GetBreed();

    cout
<<"Age = "<<nAge<<endl;
    cout
<<"Weight = "<<nWeight<<endl;
    cout
<<"BREED = "<<breed<<endl;
    
return 0;
}

代码的输出为:


原文来自:http://www.cppblog.com/kangnixi/archive/2010/02/15/107898.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值