编程题 #1
来源: POJ (http://cxsjsxmooc.openjudge.cn/test/4w3/)
注意: 总时间限制: 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
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Complex {
private:
double r, i;
public:
void Print() {
cout << r << "+" << i << "i" << endl;
}
// 在此处补充你的代码
void operator = (const char* s)
{
string str = s;
int pos = str.find("+", 0); //找到+的位置 http://www.cplusplus.com/reference/string/string/find/
string strReal = str.substr(0, pos); //分离出代表实部的字符串 http://www.cplusplus.com/reference/string/string/substr/
r = atof(strReal.c_str()); //atof库函数能将const char*指针指向的内容转换成float
string strImaginary = str.substr(pos+1, str.length()-pos-2); //分离出虚部代表的字符串
i = atof(strImaginary.c_str());
}
};
int main() {
Complex a;
a = "3+4i"; a.Print();
a = "5+6i"; a.Print();
return 0;
}
/*
查找(find)
语法:
size_type find( const basic_string &str, size_type index );
size_type find( const char *str, size_type index );
size_type find( const char *str, size_type index, size_type length );
size_type find( char ch, size_type index );
find()函数:
返回str在字符串中第一次出现的位置(从index开始查找)。如果没找到则返回string::npos,
返回str在字符串中第一次出现的位置(从index开始查找,长度为length)。如果没找到就返回string::npos,
返回字符ch在字符串中第一次出现的位置(从index开始查找)。如果没找到就返回string::npos
例如:
string str1( "Alpha Beta Gamma Delta" );
unsigned int loc = str1.find( "Omega", 0 );
if( loc != string::npos )
cout << "Found Omega at " << loc << endl;
else
cout << "Didn't find Omega" << endl;
*/
增加 return *this 的好处:
#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 string& str)
{
//string str = s;
int pos = str.find("+", 0); //找到+的位置 http://www.cplusplus.com/reference/string/string/find/
string strReal = str.substr(0, pos); //分离出代表实部的字符串 http://www.cplusplus.com/reference/string/string/substr/
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, b;
a = b = "5+6i";
a.Print();
b.Print();
return 0;
}