正文

C++个人回顾小结: 类(一)&&个人实践小结2006-12-01 16:35:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/edwardguo/21145.html

分享到:

这两天,复习了C++的类的一部分内容,当然是从最最基础的开始,以下就把一些复习的东西和大家共享一下:

一、类的定义部分:

举例如下:

#include<iostream.h>

class TDate
{
 public:
  void SetDate(int y, int m, int d);
  int IsLeapYear();
  void Print();
 private:
  int year, month, day;
};

void TDate::SetDate(int y, int m, int d)
{
 year=y;
 month=m;
 day=d;
}

int TDate::IsLeapYear()
{
 return (year%4==0&&year%100!=0)||(year%400==0);
}
void TDate::Print()
{
 cout<<year<<","<<month<<","<<day<<endl;
}
类定义注意事项:

1、类体中不允许对所定义的数据成员进行初始化,如下的定义是错误的

 class TDate

{

     public:

     private:

        int year(1998),month(4),day(9)

};

2、类中的数据成员可以是任意的,包含引用、指针等。也可以是对象:另一个类的对象

但是自身类的对象是不可以的。而自身类的指针或引用又是可以的。当一个类的对象作为这个类的成员时,如果另一个类的定义在后,需要提前说明。

class N;

class M;

{

    public:

    private:

        N n;      //n是N类的对象

};

class N

{

    public:

        void f(M m);    //m是M类的对象

};

3、类体内,一般先说明公有成员再说明私有成员

4、经常习惯性地将类定义的说明部分或者整个定义部分放到一个头文件当中。例如可将前面定义的类TDate放到一个名为tdate.h的头文件中,后面引用起来比较方便。

二、对象的定义

TDate date1,date2,*Pdate,data[31]

对象成员的表示方法:

date1.year,date1.month,date1.day

date1.SetDate(int y, int m, int d)

指向对象的指针的成员表示方法:

Pdate->year, Pdate->month, Pdate->day

或:

(*Pdate).year,(*Pdate).month,(*Pdate).day

指向对象的指针Pdate表示它的SetDate()成员函数的方法:

Pdate->SetDate(y,m,d)

或者

(*Pdate).SetDate(y,m,d)

例子:分析下列程序输出结果

void main()
{
 TDate date1,date2;
 date1.SetDate(1996,5,4);
 date2.SetDate(1998,4,9);
 int leap = date1.IsLeapYear();
 cout<<leap<<endl;
 date1.Print();
 date2.Print();
}

输出结果:

1

1996.5.4

1998.4.9

三、 对象的初始化:

例:

#include<iostream.h>

class TDate
{
 public:
  TDate(int y, int m, int d);
  ~TDate();
  void SetDate(int y, int m, int d);
  int IsLeapYear();
  void Print();
 private:
  int year, month, day;
};

TDate::TDate(int y, int m, int d)
{
 year = y;
 month = m;
 day = d;
 cout<<"Constructor called.\n";
}
TDate::~TDate()
{
 cout<<"Destructor called.\n";
}
void TDate::Print()
{
 cout<<year<<","<<month<<","<<day<<endl;
}
主函数:

void main()
{
 TDate today(1998,4,9),tomorrow(1998,4,10);
 cout<<"today is";
 today.Print();
 cout<<"tomorrow is";
 tomorrow.Print();

}

输出:

Constructor Called.

Constructor Called.

today is 1998.4.9

tomorrow is 1998.4.10

Destructor called.

Destructor called.

 

 

阅读(4525) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册