我有一類名爲幣作爲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