提问人:Stozn 提问时间:2/20/2023 最后编辑:Stozn 更新时间:2/20/2023 访问量:139
我想重载运算符<<,并且无法将'std::ostream {aka std::basic_ostream<char>}'左值绑定到'std::basic_ostream<char>&&”
I want to overloaded operator<<, and get cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
问:
我想重载运算符<<,并得到此错误。
C:\Users\Administrator\Desktop\1.cpp In function 'int main()':
22 18 C:\Users\Administrator\Desktop\1.cpp [Error] cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
39 0 D:\Dev-Cpp\MinGW64\lib\gcc\x86_64-w64-mingw32\4.9.2\include\c++\iostream In file included from D:/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++/iostream
1 C:\Users\Administrator\Desktop\1.cpp from C:\Users\Administrator\Desktop\1.cpp
602 5 D:\Dev-Cpp\MinGW64\lib\gcc\x86_64-w64-mingw32\4.9.2\include\c++\ostream [Note] initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = OutputFormatter]'
#include <iostream>
#include <iomanip>
class OutputFormatter {
public:
OutputFormatter(int width) : m_width(width) {}
template<typename T>
friend std::ostream& operator<<(std::ostream& os, const OutputFormatter& formatter) {
os << std::setw(formatter.m_width);
return os;
}
private:
int m_width;
};
OutputFormatter formatted_output(8);
int main() {
int a = 123, b = 456;
std::cout << formatted_output << a << b << std::endl;
return 0;
}
使用 TDM-GCC-4.9.2 和 -std=c++11 进行测试
我希望重载运算符<<,使所有输出变量的宽度为 8 个字符,但这似乎不可行。
答:
1赞
kaba
2/20/2023
#1
您不参与重载解析,因为您定义了模板参数(未使用)。因此,这将执行以下操作:operator<<
#include <iostream>
#include <iomanip>
class OutputFormatter {
public:
OutputFormatter(int width) : m_width(width) {}
friend std::ostream& operator<<(std::ostream& os, const OutputFormatter& formatter) {
os << std::setw(formatter.m_width);
return os;
}
private:
int m_width;
};
OutputFormatter formatted_output(8);
int main() {
int a = 123, b = 456;
std::cout << formatted_output << a << b << std::endl;
return 0;
}
您可以在编译器资源管理器上看到立竿见影的效果。
评论