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;
^
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With