c ++ struct operator:请求从非标量类型的转换

bar*_*rej 2 c++ struct operator-overloading type-conversion

我想要做的是定义一个结构等于运算符。但这似乎有什么问题。如何修复此代码?

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

int main()
{
    Rectangle rect=5;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

命令:

$ g++ -std=c++11 test.cpp
Run Code Online (Sandbox Code Playgroud)

错误:

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

πάν*_*ῥεῖ 5

对于代码,你拥有了它,你就需要指定一个合适的构造函数服用int以及

struct Rectangle {
public:
    double w;
    double h;
    Rectangle(int wh) {
        w=wh;
        h=wh;
    } 
};
Run Code Online (Sandbox Code Playgroud)

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

Rectangle rect=5; // Constructor call
Rectangle rect2; 
rect2 = 5; // Assignment operator call
Run Code Online (Sandbox Code Playgroud)