003:超简单的复数类
总时间限制:
1000ms
内存限制:
65536kB
// 在此处补充你的代码
描述
下面程序的输出是:
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; }
}; int main() { Complex a; a = "3+4i"; a.Print(); a = "5+6i"; a.Print(); return 0; }
输入
无
输出
3+4i
5+6i
样例输入
无
样例输出
3+4i 5+6i
来源
Guo Wei
注意,这里显然是一个函数的重载操作,将字符串的形式的复数表示拆分为浮点数表示,使用了STL中string模板库中函数
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Complex
{
private:
double r, i;
public:
void Print()
{
cout << r << "+" << i << "i" << endl;
}
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*指针指向的内容转换成float
string 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;
}