Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ struct operator: conversion from to non-scalar type requested

What I want to do is defining a structure equal operator. But it seems there is something wrong with that. How to fix this code?

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

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

command:

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

Error:

test.cpp: In function ‘int main()’:
test.cpp:16:17: error: conversion from ‘int’ to non-scalar type ‘Rectangle’ requested
  Rectangle rect=5;
                 ^
like image 898
barej Avatar asked Dec 04 '25 10:12

barej


2 Answers

For the code as you have it you'll need to specify an appropriate constructor taking an int as well

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

The assignment operator isn't called on initialization of that variable.

Rectangle rect=5; // Constructor call
Rectangle rect2; 
rect2 = 5; // Assignment operator call
like image 182
πάντα ῥεῖ Avatar answered Dec 07 '25 13:12

πάντα ῥεῖ


Rectangle rect=5;

To make this statement valid you have to provide single argument non-explicit constructor.

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

Remember that Rectangle rect=5 is a call to constructor rather than assignment operator.

However, you can also do away with your functions if you slightly modify your call:-

Rectangle rect1;
rect1 = 5;
like image 22
ravi Avatar answered Dec 07 '25 13:12

ravi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!