c++基础题目
杯子
定义一个Cup类,包含一个int类型的属性volume,表明杯子的容量。
定义其构造函数、析构函数和拷贝构造函数,分别产生类似样例所示的输出。
定义一个setVolume(int)函数,用于设置杯子的新容量。
输入:
400 500
输出:
A cup of 0 ml is created.
A cup of 400 ml is created.
A cup of 400 ml is copied.
A cup of 500 ml is erased.
A cup of 400 ml is erased.
A cup of 0 ml is erased.
class Cup//cup类
{
private:int volume;
public:Cup(int a=0):volume(a)//构造函数{cout<<"A cup of "<<volume<<" ml is created."<<endl;}Cup(const Cup &c):volume(c.volume)//拷贝构造函数,当main函数中出现Cup c3(c2),即类cup中含类cup的时候,就要用到拷贝构造函数{cout<<"A cup of "<<volume<<" ml is copied."<<endl;}~Cup()//析构函数{cout<<"A cup of "<<volume<<" ml is erased."<<endl;}
public:void setVolume(int s)//传一个参数{volume=s;}
};
int main()
{ Cup c1;int i, j;cin>>i>>j;Cup c2(i), c3(c2);//表示要写拷贝构造函数c3.setVolume(j);//函数中写了一个参数,代表上面的函数中要传一个参数return 0;
}