【问题标题】:c++ struct operator: conversion from to non-scalar type requestedc++ struct operator:从请求转换为非标量类型
【发布时间】:2014-12-21 08:46:10
【问题描述】:

我想做的是定义一个结构等于运算符。但这似乎有些不对劲。如何修复此代码?

struct Rectangle
{
public:
    double w;
    double h;
    Rectangle& operator=(int wh)
    {
        w=wh;
        h=wh;
        return *this;
    } 
};

int main()
{
    Rectangle rect=5;
    return 0;
}

命令:

$ g++ -std=c++11 test.cpp

错误:

test.cpp: In function ‘int main()’:
test.cpp:16:17: error: conversion from ‘int’ to non-scalar type ‘Rectangle’ requested
  Rectangle rect=5;
                 ^

【问题讨论】:

    标签: c++ struct type-conversion operator-overloading


    【解决方案1】:

    对于您拥有的代码,您需要指定一个适当的构造函数,同时采用int

    struct Rectangle {
    public:
        double w;
        double h;
        Rectangle(int wh) {
            w=wh;
            h=wh;
        } 
    };
    

    初始化该变量时不会调用赋值运算符。

    Rectangle rect=5; // Constructor call
    Rectangle rect2; 
    rect2 = 5; // Assignment operator call
    

    【讨论】:

      【解决方案2】:
      Rectangle rect=5;
      

      要使此语句有效,您必须提供单参数非显式构造函数

      struct Rectangle
      {
      public:
          Rectangle(int x) {}
      }
      

      请记住,Rectangle rect=5 是对构造函数而不是赋值运算符的调用。

      但是,如果您稍微修改调用,您也可以取消您的函数:-

      Rectangle rect1;
      rect1 = 5;
      

      【讨论】:

      • 他不能将作业作为单独的语句进行吗? Rectangle rect; rect = 5;?
      • Well mate assignment 对于相同类型的对象是有意义的......虽然你可以提供任何东西,但最好不要偏离标准。
      • 他定义的重载赋值运算符不适用?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多