Man*_*anu 1 c++ operator-overloading
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);
}
Run Code Online (Sandbox Code Playgroud)
我希望输出为:p = 5的值
应该做什么改变...并且函数应该接受传递的所有数据类型
有两种解决方案.
第一种解决方案是使其成为模板.
template <typename T>
ostream& operator<<(const T& input) const
{
cout << "In Overloaded function1\n";
return (cout << input << endl);
}
Run Code Online (Sandbox Code Playgroud)
然而,这将使a << str与a << p打印c和2.22,这是从原始的代码不同.输出99和2.
第二个解决方案是简单地添加一个重载函数const char*:
ostream& operator<<(int string)
{
cout << "In Overloaded function1\n";
return (cout << string << endl);
}
ostream& operator<<(const char* string)
{
cout << "In Overloaded function1\n";
return (cout << string << endl);
}
Run Code Online (Sandbox Code Playgroud)
这使得C字符串,一切都转换为int要A <<"版,但仅此而已-它不会'接受所传递的所有数据类型’.
顺便说一句,你已经忘记return了ostream.
| 归档时间: |
|
| 查看次数: |
224 次 |
| 最近记录: |