5-8 8:超简单的复数类

//请补足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& operator = (const char* s){
        string str = s;
        int pos = str.find('+'); //分割点
        string rr = str.substr(0, pos); //分割
        r = atof(rr.c_str()); //刚学到的 c_str()函数能返回const char*类型(可读不可改)的指向字符数组的指针
        //刚刚查了一下好像是 这些转换的库函数 参数都这个const char*类型
        string ii =str.substr(pos + 1, str.length() - 2);
        i = atoi(ii.c_str());
        return *this;
    }
};
int main() {
    Complex a;
    a = "3+4i"; a.Print();
    a = "5+6i"; a.Print();
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容