2012-04-22 119 views
1

我有一类名为币作为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的,我可以提供定义的数据类型有一些用户?

在什么情况下我应该使用这个功能?

回答

3

这种类型的运算符称为conversion function。在你的情况下,它从Dollars转换为int。该语法是标准的,你不能指定返回类型(你已经声明了类型)。

如果需要,您可以为自定义类型创建转换运算符。你可以有:

operator Yen() { ... } 
operator Euro() { ... } 

随后的Dollar一个实例可以隐式使用这些函数转换为YenEuro,而无需投(或构造在YenEuro班采取Dollar)。从 “C++ 03” 标准

实施例(§12.3.2/ 2):

class X { 
// ... 
public: 
operator int(); 
}; 

void f(X a) 
{ 
int i = int(a); 
i = (int)a; 
i = a; 
} 

C++ 11允许转换功能被标记为明确。在这种情况下,转换功能仅在直接初始化期间考虑。 (这是一般的一件好事做,以避免意外的转换,特别是对基本类型。)该示例中对于该标准(§12.3.2/ 2):

class Y { }; 
struct Z { 
explicit operator Y() const; 
}; 

void h(Z z) { 
Y y1(z);  // OK: direct-initialization 
Y y2 = z; // ill-formed: copy-initialization 
Y y3 = (Y)z; // OK: cast notation 
} 

(和C++ 11个状态表示转换函数不能声明static。)

+3

注意:C++ 11允许将'explicit'限定符应用于转换运算符。我会推荐它。 – 2012-04-22 13:30:15

+0

+1 @ @ MatthieuM。的建议,如果我使用C++ 03,我很可能会提供特殊的功能,而不是让自己处于隐藏的转换过程中。 – 2012-04-22 13:35:26

+0

谢谢@MatthieuM。,增加了一些关于这方面的信息。 – Mat 2012-04-22 13:42:58