程序设计实习MOOC / 程序设计与算法(三)---练习题

特别注意:
在这里插入图片描述
006奇怪的复制类
依旧是补充代码:
程序填空,使其输出9 22 5

#include <iostream>
using namespace std;
class Sample {
public:
	int v;
	//正确
	Sample() {};//默认构造函数必须存在
	Sample(int n) :v(n) { };
	Sample(const Sample & x){
		v = x.v + 2;
	};
};
void PrintAndDouble(Sample o)//此时将b传入该函数时,调用的是复制构造参数,也就是b到o的过程中v变成了9
{
	cout << o.v;
	cout << endl;
}
int main()
{
	Sample a(5);
	
	Sample b = a;//此时调用复制函数
	
	PrintAndDouble(b);
	Sample c = 20;
	PrintAndDouble(c);//将对象作为形参,调用复制构造函数
	Sample d;
	d = a;
	cout << d.v;
	return 0;
}

007返回什么才好

#include <iostream>
using namespace std;
class A {
public:
	int val;
	A() {
		val = 123;
	}
	A(int x) {
		val = x;
		
	};
A & GetObj() {
	return *this;
	}
};
int main()
{
	int m, n;
	A a;
	cout << a.val << endl;
	while (cin >> m >> n) {
		a.GetObj() = m;
		cout << a.val << endl;
		a.GetObj() = A(n);
		cout << a.val << endl;
	}
	return 0;
}

008:超简单的复数类

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Complex {
private:
    double r, i;
public:
    void Print() {
        cout << r << "+" << i << "i" << endl;
    }
    Complex() {};
    Complex(const char* p) {//该函数可理解为是将等号的东西作为一个参数传入函数
        r = p[0] - '0';
        i = p[2] - '0';
    };
};
int main() {
    Complex a;
    a = "3+4i"; a.Print();
    a = "5+6i"; a.Print();
    return 0;
}

在这里插入图片描述

以下语句错误,是由于y重定义。

int fun(int x, int y) { int y=10; return x+y; }

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值