文档介绍:定义并测试长方形类CRect,长方形是由左上角坐标(left, top)和右下角坐标(right, bottom)组成。
#include <>
#include <>
class CRect //定义长方形类
{
private:
int left, top, right, bottom ;
public:
void setcoord(int, int, int, int);
void getcoord(int *L, int *T, int *R, int *B)
//注意:形参为指针变量
{
*L = left; *T = top;
*R = right; *B = bottom;
}
void print(void)
{
cout<<"Area = ";
cout<<abs(right-left)*
abs(bottom-top)<<endl;
}
};
void CRect::setcoord(int L, int T, int R, int B)
{
left=L; top=T; right=R; bottom=B;
}
void main(void)
{
CRect r, rr;
int a, b, c, d ;
(100, 300, 50, 200);
( &a, &b, &c, &d );
//用变量的指针做参数,带回多个结果
cout << "left=" << a << endl;
cout << "top=" << b << endl;
cout << "right=" << c << endl;
cout << "bottom=" << d << endl;
( );
rr = r; //对象可整体赋值
( );
}
运行结果:
left=100 top=300
right=50 bottom=200
Area = 5000
Area = 5000
返回ppt讲稿
定义日期类,利用构造函数初始化数据成员。,如下:
#include <>
class Date
{
int Year, Month, Day;
public:
Date( ) //重载构造函数 1
{
Year=2010; Month=5; Day=1;
}
Date(int y) //重载构造函数 2
{
Year=y; Month=5; Day=1;
}
Date(int y, int m) //重载构造函数 3
{
Year=y; Month=m; Day=1;
}
Date(int y, int m, int d) //重载构造函数 4
{
Year=y; Month=m; Day=d;
}
void ShowDate( )
{
cout <<Year<<'.'<<Month<<'.'<<Day<<endl;
}
};
,内容如下:
#include ""
void main( )
{
Date d1; //自动调用构造函数 1
Date d2(2010); //自动调用构造函数 2
Date d3(2010, 10); //自动调用构造函数 3
Date d4(2010, 10, 6); //自动调用构造函数 4
( );
( );
( );
( );
}
运行结果是:
当然我们可以定义带缺省值的构造函数,将上述构造函数简化,下述程序的功能与上述程序相当:
#include <>
class Date
{
int Year, Month, Day;
public:
Date(int y=2010, int m=5, int d=1)
//带参数缺省值的构造函数
{
Year=y; Month=m; Day=d;
}
void ShowDate( )
{
cout <<Year<<'.'<<Month<<'.'<<Day<<endl;
}
};
void main( )