第一种方案:
[cpp] view plaincopyprint?
- #include<iostream>
- using namespace std;
- class Juxing
- {
- public:
- Juxing(int Hwidth,int Hheight);
- ~Juxing() {}
- int GetWidth() { return width; }
- int GetHeight() { return height; }
- void SetWidth(int Hwidth) { width=Hwidth; }
- void SetHeight(int Hheight) { height=Hheight; }
- int GetArea() const;
- private:
- int width,height;
- };
- Juxing::Juxing(int Hwidth,int Hheight)
- {
- width=Hwidth;
- height=Hheight;
- }
- int Juxing::GetArea() const
- {
- return width*height;
- }
- int main()
- {
- Juxing MyArea(20,30);
- int Area1,Area2,Area3;
- int width,height;
- Area1=MyArea.GetArea();
- cout<<"默认矩形的面积Area1: "<<Area1<<endl<<endl;
- MyArea.SetWidth(40);
- MyArea.SetHeight(50);
- Area2=MyArea.GetArea();
- cout<<"设定矩形的面积Area2: "<<Area2<<endl<<endl;
- cout<<"请输入矩形的长: ";
- cin>>width;
- cout<<"请输入矩形的宽: ";
- cin>>height;
- Juxing YouArea(width,height);
- Area3=YouArea.GetArea();
- cout<<"\n输入矩形的面积Area3: "<<Area3<<endl<<endl;
- return(0);
- }
第二种方案
[cpp] view plaincopyprint?
- #include<iostream>
- using namespace std;
- class Juxing
- {
- public:
- Juxing(int Hwidth,int Hheight);
- Juxing()
- {
- width=20;
- height=30;
- }
- ~Juxing() {}
- Juxing(Juxing &YouArea);//拷贝函数
- void input();//输入人员信息
- void INPUT(int Hwidth,int Hheight);//输入人员信息
- void OUTPUT();//输出人员信息
- int GetArea() const;//求面积
- private:
- int width,height;
- };
- Juxing::Juxing(int Hwidth,int Hheight)
- {
- width=Hwidth;
- height=Hheight;
- }
- void Juxing::INPUT(int Hwidth=10,int Hheight=35)
- {
- width=Hwidth;
- height=Hheight;
- }
- int Juxing::GetArea() const
- {
- return width*height;
- }
- void Juxing::input()
- {
- cout<<"请输入矩形的长: ";
- cin>>width;
- cout<<"请输入矩形的宽: ";
- cin>>height;
- }
- void Juxing::OUTPUT()
- {
- cout<<"长度为 "<<width<<" 宽度为 "<<height<<" 的面积为: ";
- }
- Juxing::Juxing(Juxing &YouArea)
- {
- width=YouArea.width;
- height=YouArea.height;
- cout<<"拷贝函数被调用!!"<<endl;
- }
- int main()
- {
- Juxing MyArea,YouArea;
- cout<<"默认数值的面积为: "<<endl;
- MyArea.INPUT();
- MyArea.OUTPUT();
- cout<<MyArea.GetArea()<<endl;
- cout<<"\n输入数值矩形的面积: "<<endl;
- MyArea.INPUT(40,80);
- MyArea.OUTPUT();
- cout<<MyArea.GetArea()<<endl;
- cout<<"\n输入数值矩形的面积: "<<endl;
- YouArea.input();
- YouArea.OUTPUT();
- cout<<YouArea.GetArea()<<endl;
- return(0);
- }
第三种方案
[cpp] view plaincopyprint?
- #include<iostream>
- using namespace std;
- class Juxing
- {
- public:
- Juxing(int len,int wid)
- {
- Length=len;
- Width=wid;
- }
- ~Juxing() {}
- int GetArea() { return Length*Width; }
- int GetLength() { return Length; }
- int GetWidth() { return Width; }
- private:
- int Length;
- int Width;
- };
- int main()
- {
- int length,width;
- cout<<"请输入矩形的长度: ";
- cin>>length;
- cout<<"请输入矩形的宽度: ";
- cin>>width;
- Juxing MyJuxing(length,width);
- cout<<"长为 "<<length<<" 宽为 "<<width<<" 的矩形的面积为: "<<MyJuxing.GetArea()<<endl;
- return(0);
- }
转自:http://blog.csdn.net/jqh2002_blog/article/details/24847849