我想知道下面代码中virtual operator float()
方法的含义,
是用来类型转换的吗?
#include <iostream>
class Frac
{
protected:
int a, b;
public:
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);
}
最佳答案
该代码定义了一个类对象到 float
的隐式转换。多变的。当你做 cout << var << endl;
operator float
在 var
上调用对象将其转换为 float
和 float
打印返回值。
virtual
关键字允许派生类覆盖基类中定义的函数。要利用此多态性,您需要更改 Print
的签名获取 Fanc 的 reference 的函数(即 Print(Franc& var)
)。然后根据传递给函数的对象类型,适当operator float
将被调用。
关于c++ - 虚拟运算符 float(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5077203/