kkk222 发表于 2019-6-8 12:02:12

c++ “=” 重载

本帖最后由 kkk222 于 2019-6-8 12:07 编辑


[*]#include <iostream>
[*]#include <cstring>
[*]using namespace std;

[*]class Complex
[*]{
[*]private:
[*]        double r, i;
[*]public:
[*]        void Print()
[*]        {
[*]                cout << r << "+" << i << "i" << endl;
[*]        }
[*]        Complex operator =(const string& s);
[*]};

[*]Complex Complex::operator =(const string& s)
[*]{
[*]        Complex temp;
[*]        int pos = s.find("+",0);
[*]        string sTmp = s.substr(0, pos);
[*]        temp.r = atof(sTmp.c_str());
[*]        sTmp = s.substr(pos + 1, s.length() - pos - 2);
[*]        temp.i = atof(sTmp.c_str());
[*]        cout << temp.r << "+" << temp.i << "i" << endl;
[*]        return temp;
[*]}

[*]int main()
[*]{
[*]        Complex a;
[*]        a = "3+4i"; a.Print();
[*]        a = "5+6i"; a.Print();
[*]        return 0;
[*]}


程序的目的是把字符串中“+”前面的数赋值给对象的实部,“+”后面到“i”前面的数赋值给虚部

程序的结果:


对象a的实部和虚部怎么都是指数?

我就是个弟弟 发表于 2019-6-8 19:55:50

为啥我编译不通过?
hello.cpp: In member function ‘Complex Complex::operator=(const string&)’:
hello.cpp:20:35: error: ‘atof’ was not declared in this scope
         temp.r = atof(sTmp.c_str());
                                 ^

我就是个弟弟 发表于 2019-6-8 20:12:34

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>

using namespace std;
class Complex
{
private:
      double r, i;
public:
      void Print()
      {
                cout << r << "+" << i << "i" << endl;
      }
      Complex & operator =(const string& s);
};
Complex & Complex::operator =(const string& s)
{
      Complex temp;
      int pos = s.find("+",0);
      string sTmp = s.substr(0, pos);
      temp.r = atof(sTmp.c_str());
      sTmp = s.substr(pos + 1, s.length() - pos - 2);
      temp.i = atof(sTmp.c_str());
      cout << temp.r << "+" << temp.i << "i" << endl;
      this->r = temp.r;
        this->i = temp.i;
        return *this;
}
int main()
{
      Complex a;
      a = "3+4i"; a.Print();
      a = "5+6i"; a.Print();
      return 0;
}

返回引用
鸣人不说暗话,我要最佳答案!!!

kkk222 发表于 2019-6-9 14:38:02

我就是个弟弟 发表于 2019-6-8 20:12
返回引用
鸣人不说暗话,我要最佳答案!!!

16行代码那里Complex & operator 的‘&’是引用吗?
为什么要返回 *this 而不能返回temp?

我就是个弟弟 发表于 2019-6-9 20:06:45

kkk222 发表于 2019-6-9 14:38
16行代码那里Complex & operator 的‘&’是引用吗?
为什么要返回 *this 而不能返回temp?

htt*ps://w*ww.cnb*logs.com/zpc*dbky/p/502*7481.html
删掉星星
页: [1]
查看完整版本: c++ “=” 重载