1

私はドルという名前のクラスを持っています

    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() { ... }

次に、これらの関数を使用して、キャスト (またはまたはクラスでa を受け取るコンストラクター) を必要とせずに、 のインスタンスを暗黙的にまたはDollarに変換できます。YenEuroDollarYenEuro

「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 では、変換関数をexplicitとしてマークできます。その場合、変換関数は直接初期化中にのみ考慮されます。(これは一般に、特に基本的な型の場合、予期しない変換を避けるために行うべき良いことです。) そのための標準の例は (§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 に答える