重载运算符+复制构造函数(POJ C++ 第4周)

4w3:第四周程序填空题1

描述

下面程序的输出是:

3+4i

5+6i

请补足Complex类的成员函数。不能加成员变量。

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class Complex 
{
private:
	double r, i;
public:
	void Print() {
		cout << r << "+" << i << "i" << endl;
	}

	// 在此处补充你的代码

	Complex() :r(0), i(0){}//默认构造函数
	Complex& operator=(char* ch)//重载复制构造函数
	{
		int ii = 0;
		char cr[100];
		while (*ch != '+')
		{
			cr[ii] = *ch;
			ch++;
			ii++;
		}
		ch++;

		r = atoi(cr);
		i = atoi(ch);          // atoi(6i)  得到结果为6;

		return *this;
};

int main()
{
	Complex a;//默认构造函数
	a = "3+4i"; //重载复制构造函数
	a.Print();
	a = "5+6i";
	a.Print();
	return 0;
}

4w4:第四周程序填空题2

问题描述

下面的MyInt类只有一个成员变量。MyInt类内部的部分代码被隐藏了。假设下面的程序能编译通过,且输出结果是:

4,1

请写出被隐藏的部分。(您写的内容必须是能全部放进 MyInt类内部的,MyInt的成员函数里不允许使用静态变量)。

#include <iostream>
using namespace std;
class MyInt  {
	int nVal;
public:
	MyInt(int n) { nVal = n; }
	int ReturnVal() { return nVal; }
	// 在此处补充你的代码
	//重载运算符-
	MyInt& operator-(int i)
	{
		nVal -= i;
		return *this;
	}
};
int main()  {
	MyInt objInt(10);
	objInt - 2 - 1 - 3;
	cout << objInt.ReturnVal();
	cout << ",";
	objInt - 2 - 1;
	cout << objInt.ReturnVal();
	return 0;
}

3w8:第三周程序填空题3

描述

扫描二维码关注公众号,回复: 2412212 查看本文章

下面程序的输出是:

10

请补足Sample类的成员函数。不能增加成员变量。

#include <iostream>
using namespace std;

class Sample
{
public:
	int v;
	Sample(int n) :v(n) { }
	//复制构造函数
	Sample(const Sample& a)
	{
		v = 2 * a.v;
	}

};
int main() {
	Sample a(5);//构造函数
	Sample b = a;//初始化,复制构造函数
	cout << b.v;
	return 0;
}

20151:补足程序1(输入输出运算符重载)

描述

补足程序,使得下面程序输出的结果是:

****100

#include <iostream>
#include <string>
using namespace std;

// 在此处补充你的代码
ostream & operator <<(ostream &o, string (*s)())
{
o << s();
return o;
}

ostream & operator <<(ostream &o, int (*s)())
{
o << s();
return o;
}




string Print1()
{
return "****";
}
int Print2()
{
return 100;
}


int main()
{
cout << Print1 << Print2 << endl;
return 0;
}

猜你喜欢

转载自blog.csdn.net/try_again_later/article/details/81129158