C++ 类模板

下面给出了关于类成员的初始化,指向类成员的指针,const用法和引用用法的模板。

#include<iostream> //不是iostream.h
using namespace std;

class BOX
{
  public:
    BOX (int h=10, int w=20, int l=30);//带参数的构造函数,并指定h,w,l的默认值

    int volume();

    void outputoutput();

    void const_outputoutput() const; //const 要放在最后

    void get_time();
    ~BOX() // Destructor 析构函数,当对象生命周期技术后将被执行。本例中,main的return执行后main中声明的对象生命周期结束
    { cout << "Destructor called." << endl; }

    int length;

  private:
    const int height; //常数据成员,只能通过构造函数初始化,而且初始化后值不能被改变
    int width;

};

/*BOX::BOX(int h, int w, int l) //在类外定义构造函数
{
  height=h;
  width =w;
  length=l;
}*/

//构造函数更加清爽的写法。如果参数中有const常量,那只能使用这种构造函数写法,不能使用上面的写法
BOX::BOX(int h, int w, int l):height(h), width(w), length(l){}

void BOX::outputoutput()
{
  cout<<"outputoutput"<<endl;
}

void BOX::const_outputoutput() const //const 要放在最后
{
  cout<<"const_outputoutput"<<endl;
}


int BOX::volume()
{
  return (height * width * length);
}

int main()
{

  /////////////////类成员初始化///////////////////

  BOX box1(12, 25, 30); //建立对象box1,并指定box1的长宽高
  cout << "The volume of box1 is " <<box1.volume()<< endl;

  BOX box2(15, 30, 21); //建立对象box2,并指定box2的长宽高
  cout << "The volume of box2 is " <<box2.volume()<< endl;

  BOX box3; //建立对象box3,并使用默认参数
  cout << "The volume of box3 is " <<box3.volume()<< endl;

  BOX box4(100); //建立对象box4,指定h=100,其他参数使用默认参数
  cout << "The volume of box4 is " <<box4.volume()<< endl;

  BOX box5(100, 200); //建立对象box5,指定h=100,w=200, 其他参数使用默认参数
  cout << "The volume of box5 is " <<box5.volume()<< endl;

  BOX box[3]={
  BOX(1,2,3), BOX(10,20,30), BOX(100,200,300)
  }; // 定义对象box数组

  cout<<"volume of box[0] is "<<box[0].volume()<<endl;
  cout<<"volume of box[1] is "<<box[1].volume()<<endl;
  cout<<"volume of box[2] is "<<box[2].volume()<<endl;

  /////////////////指向成员对象的指针///////////////////
  BOX box6;
  int *p1 = &box6.length; //定义指向整形数据的指针变量p1,并使p1指向box6.length
  cout << *p1 << endl;

  BOX *p2 = &box6; //定义指向BOX类对象的指针变量p2,并使p2指向box6
  p2->outputoutput();//或者用(*p2).outputoutput()

  void(BOX::*p3)();//定义指向BOX类公用成员函数的指针变量p3
  p3 = &BOX::outputoutput;//使p3指向BOX类公用成员函数outputoutput
  //void(BOX::*p3)()=&BOX::outputoutput, 上两行的清爽版写法
  (box6.*p3)();//调用box6中p3所指向的成员函数

  /////////////////公用数据的保护///////////////////

  //常对象,对象中所有数据成员的值都不能被修改,而且不能调用该对象的非const型的成员函数
  BOX const box7; //或者const BOX box7
  box7.const_outputoutput();
  //box7.outputoutput();//报错,因为outputoutput()未被声明为const


  /////////////////引用///////////////////
  BOX box8;
  BOX &r_box = box8;
  cout << "The volume of box8 is " <<r_box.volume()<< endl;

//int try_get_private = box1.height; // 非法,不能获取private的参数

  return 0;
}

 

posted on 2013-01-02 12:44  cosmo89929  阅读(237)  评论(0)    收藏  举报

导航