C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  117 Posts :: 2 Stories :: 61 Comments :: 0 Trackbacks

常用链接

留言簿(8)

搜索

  •  

最新评论

阅读排行榜

评论排行榜

 

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

      但是在C++structclass意义一样,唯一不同就是struct里面默认的访问控制是publicclass中默认的访问控制是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;
}

代码的输出为:


想要获得更多内容,可点击:《Visuanl C++代码参考与技巧大全》学习笔记——索引随笔
posted on 2010-02-15 17:20 烟皑 阅读(732) 评论(0)  编辑 收藏 引用 所属分类: 《Visual C++代码参考与技巧大全》学习笔记

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理