我有一类名为币作为ostream的操作符重载
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的,我可以提供定义的数据类型有一些用户?
在什么情况下我应该使用这个功能?
注意:C++ 11允许将'explicit'限定符应用于转换运算符。我会推荐它。 – 2012-04-22 13:30:15
+1 @ @ MatthieuM。的建议,如果我使用C++ 03,我很可能会提供特殊的功能,而不是让自己处于隐藏的转换过程中。 – 2012-04-22 13:35:26
谢谢@MatthieuM。,增加了一些关于这方面的信息。 – Mat 2012-04-22 13:42:58