How to overload operators with a built-in return type?

后端 未结 4 821
时光说笑
时光说笑 2021-01-23 06:56

Say I have a class, that wraps some mathematic operation. Lets use a toy example

class Test
{
public:
   Test( float f ) : mFloat( f ), mIsInt( false ) {}

   fl         


        
4条回答
  •  北海茫月
    2021-01-23 07:27

    You can't "overload/add" operators for basic types, but you can for your type Type. But this shall not be operator = but operator >> - like in istreams.

    class Test
    {
    public:
       float mFloat;
       int   mInt;
       bool  mIsFloat;
       Test& operator >> (float& v) { if (mIsFloat) v = mFloat; return *this; }
       Test& operator >> (int& v) { if (!mIsFloat) v = mInt; return *this; }
    };
    

    Then you can:

    int main() {
      float v = 2;
      Test t = { 1.0, 2, false };
      t >> v; // no effect
      t.mIsFloat = true;
      t >> v; // now v is changed
    }   
    

    Update

    I want to do something like:

    updateTime = config["system.updateTime"];
    

    Then with my proposal, you cam:

    config["system.updateTime"] >> updateTime;
    

提交回复
热议问题