gpt4 book ai didi

c++ - ostream 运算符重载

转载 作者:行者123 更新时间:2023-11-30 03:02:17 26 4
gpt4 key购买 nike

我有一个名为 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 重载时它不会去那里。

我的困惑

为什么 operator int() 函数没有任何返回类型,据我所知,C++ 中的所有函数都应该有返回类型或 void,构造函数除外。

我可以在那里提供一些用户定义的数据类型而不是 int 吗?

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

最佳答案

这种运算符称为 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。)

关于c++ - ostream 运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10268200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com