第四章课后练习
习题
4-14题目:定义一个Tree类,有成员树龄ages,成员函数grow对ages加上years,age()显示tree对象的ages对象的ages的值。
代码部分:
#include<iostream> using namespace std; class Tree { private: int ages; public: Tree(int a) { ages = a; } void grow(int years) { cout << ages + years; } }; int main() { int a; cin >> a; Tree x(a); x.grow(3); return 0; }
题目描述:定义一个负数类Complex,似的下面的代码能够工作:
Complex c1(3,5);//用复数3+5i初始化c1;
Complex c2=4.5;//用实数4.5初始化c2
c1.add(c2);//将c2与c1相加,结果保存在c1中
c1.show();//将c1输出
设计思路:
1.定义一个Complex类包括a,b两个私有成员,和共有成员函数带有默认值为0的构造函数,复制构造函数和add函数show函数。
代码部分:
#include<iostream> using namespace std; class Complex { private: double a; double b; public: Complex(double c = 0, double d = 0) { a = c; b = d; } Complex(Complex& p) { a = p.a; b = p.b; } void add(Complex& p) { a += p.a; b += p.b; } void show() { cout << a << "+" << b << "i" << endl; } }; int main() { Complex c1(3, 5); Complex c2 = 4.5; c1.add(c2); c1.show(); return 0; }
浙公网安备 33010602011771号