运算符重载-编程题#1(C++程序设计第4周)

来源:互联网 发布:mac装windows虚拟机 编辑:程序博客网 时间:2024/05/18 10:39

编程题 #1

来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)

注意: 总时间限制: 1000ms 内存限制: 65536kB

描述

下面程序的输出是:

3+4i

5+6i

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Complex {
private:
double r,i;
public:
void Print() {
cout << r << "+" << i << "i" << endl;
}
//
};
int main() {
Complex a;
a = "3+4i"; a.Print();
a = "5+6i"; a.Print();
return 0;
}

输入

输出

3+4i

5+6i

样例输入

1

样例输出

1
2
3+4i
5+6i

代码:

#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& operator = (const char* s){string str = s;int pos = str.find("+", 0);string strReal = str.substr(0, pos);//分离出代表实部的字符串r = atof(strReal.c_str());//atof库函数能将const char*指针指向的内容转换成floatstring strImaginary = str.substr(pos + 1, str.length() - pos - 2);//分离出虚部代表的字符串i = atof(strImaginary.c_str());return *this;}};int main() {Complex a;a = "3+4i"; a.Print();a = "5+6i"; a.Print();return 0;}


0 0
原创粉丝点击