作业1:
1.定义一个矩形类Rec,包含私有属性length、width,包含公有成员方法:
void set_length(int l);//设置长度
Void set_width(int w);//设置宽度
Int get_length();//获取长度,将长度的值返回给调用处
Int get_width();//获取宽度,将宽度的值返回给调用处
Void show();//输出周长和面积
#include <iostream>
using namespace std;
class Rec{
const int length;
int width;
public:
Rec():length(5),width(6)
{
cout<<"无参构造:length="<<length<<"width="<<width<<endl;
}
Rec(int len,int wid):length(len)
{
width=wid;
cout<<"有参构造1:length="<<length<<"width="<<width<<endl;
}
Rec(int len):length(len)
{
cout<<"有参构造2:length="<<length<<"width="<<width<<endl;
}
//void set_length(int l);
void set_width(int w);
int get_length();
int get_width();
void show();
};
void Rec::set_width(int w)
{
width=w;
}
int Rec::get_length()
{
return length;
}
int Rec::get_width()
{
return width;
}
void Rec::show()
{
cout<<"周长:"<<length*2+width*2<<endl;
cout<<"面积:"<<length*width<<endl;
}
int main()
{
Rec rec;
cout<<"length="<<rec.get_length()<<endl;
cout<<"width="<<rec.get_width()<<endl;
rec.show();
cout << "****************" << endl;
Rec rec1(4,1);
cout<<"length="<<rec1.get_length()<<endl;
cout<<"width="<<rec1.get_width()<<endl;
rec1.show();
cout << "****************" << endl;
Rec rec2(3);
cout<<"length="<<rec2.get_length()<<endl;
cout<<"width="<<rec2.get_width()<<endl;
rec2.show();
return 0;
}
作业2:
2.定义一个圆类,包含私有属性半径r,公有成员方法:
Void set_r(int r);//获取半径
Void show();//输出周长和面积,show函数中需要一个提供圆周率的参数PI,该参数默认值3.14
#include <iostream>
using namespace std;
class Yuan{
int &r;
public:
Yuan(int &r1):r(r1)
{
cout<<"有参构造r="<<r<<endl;
}
void set_r(int &r);
void show(double PI=3.14);
};
void Yuan::set_r(int &r)
{
this->r=r;
}
void Yuan::show(double PI)
{
double l=2*PI*r;
double a=PI*r*r;
cout<<"周长:"<<l<<endl;
cout<<"面积:"<<a<<endl;
}
int main()
{
int r=1;
Yuan yuan(r);
yuan.show();
int r1=2;
yuan.set_r(r1);
yuan.show();
cout << "Hello World!" << endl;
return 0;
}
作业3:
定义一个Car类,包含私有属性,颜色color,品牌brand,速度speed,包含公有成员方法:
Void display();//显示汽车的品牌,颜色和速度
Void acc(int a);//加速汽车
set函数,设置类中的私有属性
#include <iostream>
using namespace std;
class Car{
string color;
string brand;
int speed;
public:
Car()
{
cout<<"无参构造"<<endl;
}
Car(string color,string brand,int speed)
{
this->color=color;
this->brand=brand;
this->speed=speed;
cout<<"有参构造"<<endl;
}
void set(string,string,int);
void display();
void acc(int a);
};
void Car::set(string color,string brand,int speed)
{
this->color=color;
this->brand=brand;
this->speed=speed;
}
void Car::display()
{
cout<<"color:"<<color<<endl;
cout<<"brand:"<<brand<<endl;
cout<<"speed:"<<speed<<endl;
}
void Car::acc(int a)
{
speed+=a;
}
int main()
{
Car car;
car.set("红色","车",100);
car.display();
car.acc(1);
car.display();
Car car1("白色","奥迪",200);
car1.display();
car1.acc(2);
car1.display();
cout << "Hello World!" << endl;
return 0;
}