Reputation: 996
For example, I have a class called Length
.
class Length {
public:
static const float METER_TO_FLOAT_RATIO;
Length();
void setValue(float valueInMeter);
operator const float();
private:
float valueInMeter_;
};
const float METER_TO_FLOAT_RATIO= 10;
Length::Length() {}
Length::operator const float() {
return this->valueInMeter_ * METER_TO_FLOAT_RATIO;
}
void drawRectangle(Length width, Length height) {
//draw width * height rectangle
}
int main() {
Length width, height;
width = 20.0f;
height = 10.0f;
drawRectangle(width, height);
return 0;
}
I asked this question to figure it out how to convert implicitly from Length
to float
but I forgot to or didn't ask about how to convert backward. The method which converts backward will call this statement:
valueInMeter_ = valueInFloat_ / METER_TO_FLOAT_RATIO; //valueInFloat_ is the parameter
Upvotes: 0
Views: 48
Reputation: 206567
There are two ways that I can think of:
Use a converting constructor.
Length(float val);
Use an overloaded assignment operator.
Length& operator=(float val);
If you add the converting constructor, you won't need the assignment operator.
Upvotes: 3