1

我有一个名为 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 吗?

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

4

1 回答 1

3

这种类型的运算符称为转换函数。在您的情况下,它从 转换Dollarsint。该语法是标准的,您不能指定返回类型(您已经说明了类型)。

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

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

然后可以使用这些函数将 of 的实例Dollar隐式转换为 a Yenor Euro,而无需强制转换(或DollarYenorEuro类中采用 a 的构造函数)。

来自“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。)

于 2012-04-22T13:20:11.717 回答