代码之家  ›  专栏  ›  技术社区  ›  zmbush

C++:重载运算符=

  •  5
  • zmbush  · 技术社区  · 15 年前

    好的,我有一个类具有“弱类型”,即它可以存储许多不同的类型,定义如下:

    #include <string>
    
    class myObject{
       public:
          bool isString;
          std::string strVal;
    
          bool isNumber;
          double numVal;
    
          bool isBoolean;
          bool boolVal;
    
          double operator= (const myObject &);
    };
    

    double myObject::operator= (const myObject &right){
       if(right.isNumber){
          return right.numVal;
       }else{
          // Arbitrary Throw.
          throw 5;
       }
    }
    

    这样我就可以做到:

    int main(){
       myObject obj;
       obj.isNumber = true;
       obj.numVal = 17.5;
       //This is what I would like to do
       double number = obj;
    }
    

    error: cannot convert ‘myObject’ to ‘double’ in initialization 
    

    在作业上。

    我也尝试过:

    int main(){
       myObject obj;
       obj.isNumber = true;
       obj.numVal = 17.5;
       //This is what I would like to do
       double number;
       number = obj;
    }
    

    我得到:

    error: cannot convert ‘myObject’ to ‘double’ in assignment
    

    operator=

    5 回复  |  直到 14 年前
        1
  •  12
  •   CB Bailey    15 年前

    超载 operator=

    如果要提供到其他类型的隐式转换,则需要提供转换运算符,例如。

    operator double() const
    {
        if (!isNumber)
            throw something();
        return numVal;
    }
    
        2
  •  7
  •   Kornel Kisielewicz    15 年前

    您真正需要的是转换运算符。

    operator double() const { return numVal; }
    operator int() const { ...
    

    也就是说,你可能会 boost::variant

        3
  •  2
  •   jspcal    15 年前

    为此,您需要实现一个从对象到可以转换为双精度的对象的转换操作符

        4
  •  2
  •   goldPseudo    15 年前

    的返回值 operator=()

    例如:

    int main() {
      myObject obj, obj2;
      obj.isNumber = true;
      obj.numVal = 17.5;
      obj2.operator=(obj); // equivalent to obj2 = obj
    }
    

    number = obj; 不起作用是因为你已经定义了 myObject::operator=() 鉴于 number 将使用 double::operator=() (好的,从技术上讲,没有 double::运算符=() 因为这是一个基本类型,而不是一个类…请在这里与我一起工作)。

    一个有趣的注意事项是,此函数的行为与任何其他函数一样,返回值( return right.numval; )未使用时将被忽略。但是,返回值可以像任何其他函数的返回值一样分配或使用,因此如果您确实需要,可以执行以下操作:

    int main() {
      myObject obj, obj2;
      obj.isNumber = true;
      obj.numVal = 17.5;
      double number;
      // number = obj; still won't work.
      number = obj2 = obj; // equivalent to number = obj2.operator=(obj)
    }
    

    这是非常有用的。正如其他人提到的,你真的想调查 转换运算符 当试图分配 myObject 对象转换为基本类型。

        5
  •  -1
  •   Pavel Radzivilovsky    15 年前

    要使类可分配给double,必须以不同的方式定义运算符=。

    double operator=(myclass&) 这是错误的。

    可以使用的是类外的friend操作符,它接受double和myclass&。

    推荐文章