virtual operator float()
I'd like to know the meaning of the virtual operator float()
method in the following code ,
is it used for casting ?
#include <iostream>
class Frac
{
protected:
int a, b;
publi开发者_如何学编程c:
Frac(int x, int y):a(x),b(y)
{}
virtual operator float()
{ return (float)a/b; }
friend void Print(Frac var)
{ std::cout << var << endl; }
};
class TwiceFrac : public Frac
{
public:
TwiceFrac():Frac(1,2)
{}
virtual operator float()
{ return (float)a/b * 2; }
};
int main()
{
TwiceFrac obj;
Print(obj);
}
The code defines an implicit conversion for an object of the class to a float
variable. When you do cout << var << endl;
the operator float
is invoked on var
object to convert it to the float
and the float
value returned is printed.
The virtual
keyword allows the derived class to override the function defined in the base class. To take advantage of this polymorphism you need to change the signature of Print
function to take the reference of Fanc (i.e. Print(Franc& var)
). Then depending on the type of the object passed to the function, appropriate operator float
will be called.
Yes, you are right. this operator used for casting :)
This won't work because you slice in the Print function.
You need to get your Print function to take a reference. More preferably make it take a const reference and make your implicit type conversion method also const.
精彩评论