我有一个名为 Dollars 的课程
class Dollars
{
private:
int dollars;
public:
Dollars(){}
Dollars(int doll)
{
cout<<"in dollars cstr with one arg as int\n";
dollars = doll;
}
Dollars(Cents c)
{
cout<<"Inside the constructor\n";
dollars = c.getCents()/100;
}
int getDollars()
{
return dollars;
}
operator int()
{
cout<<"Here\n";
return (dollars*100);
}
friend ostream& operator << (ostream& out, Dollars& dollar)
{
out<<"output from ostream in dollar is:"<<dollar.dollars<<endl;
return out;
}
};
void printDollars(Dollars dollar)
{
cout<<"The value in dollars is "<< dollar<<endl;
}
int main()
{
Dollars d(2);
printDollars(d);
return 0;
}
在上面的代码中,如果我删除了重载的 ostream 运算符,那么它将转到
operator int()
{
cout<<"Here\n";
return (dollars*100);
}
但是在提供 ostream 重载时,它不会去那里。
我的困惑
Why isn't there any return type for operator int() function as far as my understanding says that all functions in C++ should have a return type or a void except the constructors.
我可以在那里提供一些用户定义的数据类型而不是 int 吗?
在什么情况下我应该使用这个功能?