I'm sorry if this has been asked already, but I'm still learning C++ and struggling with a bit of syntax.
I'm supposed to overload the type conversion operator, so that it will accept an object and return an int value, based on a protected int inside that object.
Header file:
definitions.h
class Baseballs
{
protected:
int currentValue;
public:
Baseballs(int);
int operator= (Baseballs&); // ??????
}
Methods:
methods.cpp
#include "definitions.h"
Baseballs::Baseballs(int value)
{
currentValue = value;
}
int Baseballs::operator=(Baseballs &obj) // ??????
{
int temp = obj.currentValue;
return temp;
}
So in main.cpp, if I create an object:
Baseballs order(500);
Then 500 is assigned to currentValue
. I need to be able to assign that to an int variable, and ultimately print it for verification, such as:
int n = order;
cout << n;
What I'm having trouble with is the syntax for overloading =
. Can someone tell me what the proper syntax for the definition and method should be?
The overloaded =
is really to assign to objects of the same type. Ex:
order = another_order;
What you are looking for is an overloaded conversion operator.
operator int() { return currentvalue; }
However this is generally not regarded as good practice, due to unknown conversions. An explicit
overload is much safer:
explicit operator int() {...}
However you would need to do:
int n = static_cast<int>(order);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.