问题描述
我正试图超载
操作员.例如
给出我必须以格式打印
<literal_valueof_a><"\n>
<literal_valueof_b><"\n">
<"\n">
我试图超载<<运算符,将字符串作为参数,但不起作用.所以我猜是文字
I tried to overload << operator giving string as argument but it is not working. So I guess literal
不是字符串.如果不是,那是什么.以及如何超载呢?请帮助;
is not a string. If it is not then what is it. And how to overload it?Kindly help;
完整代码
//Begin Program
// Begin -> Non - Editable
#include <iostream>
#include <string>
using namespace std;
// End -> Non -Editable
//---------------------------------------------------------------------
// Begin -> Editable (I have written )
ostream& operator << (ostream& os, const string& str) {
string s = " ";
if(str == " ") {
os << '\n';
}
else {
for(int i = 0; i < str.length(); ++i)
os << str[i];
}
return os;
}
// End -> Editable
//--------------------------------------------------------------------------
// Begin -> No-Editable
int main() {
int a, b;
double s, t;
string mr, ms;
cin >> a >> b >> s >> t ;
cin >> mr >> ms ;
cout << a << " " << b << " " ;
cout << s << " " << t << " " ;
cout << mr << " " << ms ;
return 0;
}
// End -> Non-Editable
//End Program
输入和输出输入
30 20 5.6 2.3 hello world
输出
30
20
5.6
2.3
hello
world
推荐答案
" "
是长度为1的字符串文字,因此类型为const char[2]
. std::string
不相关.
" "
is a string-literal of length one, and thus has type const char[2]
. std::string
is not related.
理论上,因此您可以将其重载为:
Theoretically, you could thus overload it as:
auto& operator<<(std::ostream& os, const char (&s)[2]) {
return os << (*s == ' ' && !s[1] ? +"\n" : +s);
}
虽然胜过其他所有重载,但现在事情真的变得多毛了.问题在于,即使在模板中,some_ostream << " "
也很常见,并且现在不再解析为调用标准功能.现在,这些模板在受影响的翻译单元中的定义与未受影响的翻译单元中的定义不同,从而违反了一个定义规则.
While that trumps all the other overloads, now things get really hairy. The problem is that some_ostream << " "
is likely not uncommon, even in templates, and now no longer resolves to calling the standard function. Those templates now have a different definition in the affected translation-units than in non-affected ones, thus violating the one-definition-rule.
最好修改当前流式传输空格字符的代码.
或者,编写自己的流缓冲区,将其按需转换为换行符.
Preferably, modify your code currently streaming the space-character.
Alternatively, write your own stream-buffer which translates it as you wish, into newline.
这篇关于过载<<操作员更改""到"\ n"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!