在 C++ 中使用运算符重载
class A
{
public:
ostream& operator<<(int string)
{
cout << "In Overloaded function1\n";
cout << string << endl;
}
};
main()
{
int temp1 = 5;
char str = 'c';
float p= 2.22;
A a;
(a<<temp1);
(a<<str);
(a<<p);
(a<<"value of p=" << 5);
}
我希望输出为: p=5 的值
应该做什么更改...并且该函数应该接受传递的所有数据类型
class A
{
public:
ostream& operator<<(int string)
{
cout << "In Overloaded function1\n";
cout << string << endl;
}
};
main()
{
int temp1 = 5;
char str = 'c';
float p= 2.22;
A a;
(a<<temp1);
(a<<str);
(a<<p);
(a<<"value of p=" << 5);
}
I want the output to be: value of p=5
What changes should is do...and the function should accept all data type that is passed
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有2种解决方案。
第一个解决方案是使其成为模板。
但是,这将使
a << str
和a << p
打印c
和2.22
,这与您的原始代码不同。输出99
和2
。第二种解决方案是简单地为
const char*
添加一个重载函数:这允许 C 字符串和所有可转换为
int
的内容成为A <<
>'ed,但仅此而已 - 它不会“接受传递的所有数据类型”。顺便说一句,您忘记
返回
ostream
。There are 2 solutions.
First solution is to make it a template.
However, this will make the
a << str
anda << p
printc
and2.22
, which is different from your original code. that output99
and2
.The second solution is simply add an overloaded function for
const char*
:This allows C strings and everything convertible to
int
to beA <<
'ed, but that's all — it won't "accept all data type that is passed".BTW, you have forgotten to
return
theostream
.