C++之数据类型,类

注意点:

  同一个成员函数只能被申明或定义一次!!!

  定义完类时,内存并未为其分配存储空间,实例对象时才有分配。

  class声明的类,如果不做private 或public声明,系统默认为private

  struct声明的类,。。。。。。。public

  union声明的类,。。。。。。。public

  类中定义方法可以直接 void func(){} ,

  如果在class{}外部定义该类的方法就可以用void className::func(){} , 前提是该方法必须先在class{}中声明。!!!

1.定义:

class Goods{

  public:

    char Nmae[10];      //定义成员变量
  private:
    int Amount;
    float Price;
    float Total_value;
  public:
    void getName(char*);    //申明成员函数,可以不写方法体,

    Goods(){           //构造函数,不能指定类型!!!void都不能写
      cout<<"hehe";
    }

    void Goods::registerGoods(char* name , int amount , float price){ //定义成员函数(或者直接void registerGoods(char *param.....)定义
      strcpy(Name,name);
      Amount    = amount;
      Price    = price;
    }

    void Goods::countTotal(void){
      Total_value    = Price*Amount;
    }

    float Goods::getTotal_value(void){
      return Total_value;
    }

    float Goods::getPrice(void){
      return Price;
    }

    ~Goods(){           //析构函数,不能指定类型!!!void都不能写
      cout<<"系统有默认的构造和析构函数";
    }
};

 

 

2,实例对象

  

Goods Cars;

 

3.对象调用成员函数

int main ()
{
    Goods Car;
    char name[10];
    int amount;
    float price;
    float total=1;
    cout<<"输入车辆名称";
    cin.getline(name,10);
    cout<<"输入数量和价格";
    cin>>amount>>price;
    cout<<"total is"<<total<<"\n";

    Car.registerGoods(name,amount,price);  //调用成员函数
    Car.countTotal();              //调用成员函数
    total = Car.getTotal_value();        //调用成员函数

    cout<<"车辆名称是"<<Car.Name<<"\n";    //调用成员变量        (只能访问public 的)
    cout<<"车辆单价是"<<Car.getPrice()<<"\n";

}

 

4.类的继承

 父类(基类):

class animal{
private :
    char *Name;
    int Foot;
    int Eye;
    int Hear;
public :
    animal(char *name , int foot , int eye , int hear){    
        Name = name;
        Foot = foot;
        Eye     = eye;
        Hear = hear;
    };
    ~animal(){};
    int getFoot(){
        return Foot;
    }
};

子类(派生类):

class cat:public animal{  //cat继承animal类
public:
    cat::cat(char *name , int foot , int eye , int hear):animal(name , foot , eye , hear){  //调用父类的构造函数
        cout<<"im "<<name;
    }
};

 

posted on 2014-11-04 17:26  allen__  阅读(273)  评论(0编辑  收藏  举报

导航