C++程序设计第四版部分作业题

4-20定义一个复数类Complex,使得下面的代码能够工作。 Complex c1(3,5); //用复数3+5i初始化c1 Complex c2=4.5; //用实数4.5初始化c2

c1.add(c2); //将c1与c2相加,结果保存在c1中 c1.show(); //将c1输出(这时的结果应该是7.5+5i) 源代码程序:

#include using namespace std; class Complex{ public: Complex(float r1,float i1);//构造函数 Complex(float r1);

void add(Complex &c); //复制构造函数 void show(); private: float r; float i;};

Complex::Complex(float r1,float i1)//构造函数的具体实现 { r=r1; i=i1; }

void Complex::add(Complex &c)//复制构造函数的具体实现 { r+=c.r; i+=c.i; }

void Complex::show()//类成员函数的具体实现 { cout<0 ? '+':'-')<

Complex::Complex(float r1)//构造函数的具体实现 { r=r1; i=0; }

int main() { Complex c1(3,5);//对象的初始化

Complex c2=4.5;

c1.add(c2);//函数的形参为类的对象,当函数调用时,复制构造函数被调用 c1.show(); return 0;

}

运行结果

5-14用C++定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和. 源代码程序:#include

#include using namespace std; class Car; class Boat{ public: int weight; friendinttotalWeight(Boat &boat, Car &car); Boat(int a):weight(a){}}; class Car{

public: int weight; friendinttotalWeight(Boat &boat, Car &car); Car(int a):weight(a){}};

inttotalWeight(Boat &boat, Car &car) { returnboat.weight + car.weight; }

void main()

{ Boat boat(10); Car car(10);

cout<<\

cout<

运行结果

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4