CPP 怎么让自己的类提供<<运算符

如果是下面这样的话,只需要提供一个全局函数就可以让自己的类输出到std::cout,也可以从std::cin输入数据到自己的类:

#include <iostream>
using namespace std;
 
class Complex
{
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0)
    {  real = r;   imag = i; }
    friend ostream & operator << (ostream &out, const Complex &c);
    friend istream & operator >> (istream &in,  Complex &c);
};
 
ostream & operator << (ostream &out, const Complex &c)
{
    out << c.real;
    out << "+i" << c.imag << endl;
    return out;
}
 
istream & operator >> (istream &in,  Complex &c)
{
    cout << "Enter Real Part ";
    in >> c.real;
    cout << "Enter Imagenory Part ";
    in >> c.imag;
    return in;
}
 
int main()
{
   Complex c1;
   cin >> c1;
   cout << "The complex object is ";
   cout << c1;
   return 0;
}



但是我现在需要自己的类能通过<<得到数据,比如上面的类 Complex:

class Complex;
Complex c;
c << 1;

假设1存储在real里

现在我是把"123"给对象c,要怎么写呢?

阅读 1.7k
1 个回答

不知道你是不是这个意思,用C++的标识符重载就行了,重载<<号,下面是简单的例子代码

#include <iostream>
using namespace std;
class Complex
{
public:
    float real;
    void operator <<(float r)
    {
        real = r;
    }
};
int main()
{
    Complex c;
    c << 1.5;
    cout<<c.real;
    return 0;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题