簡體   English   中英

ostream運算符重載

[英]ostream operator Overloading

我有一個名為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嗎?

在什么情況下我應該使用此功能?

這種類型的運算符稱為轉換函數 在您的情況下,它從Dollars轉換為int 該語法是標准的,您不能指定返回類型(您已經說明了類型)。

如果需要,您可以為自定義類型創建轉換運算符。 你可以有:

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

然后可以使用這些函數將Dollar的實例隱式轉換為YenEuro ,而無需使用Yen轉換(或構造函數在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指出轉換函數不能聲明為靜態 。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM