在创建一个简单的异常类扩展(我可以更容易地构造错误消息)时,我将错误隔离为以下简单代码:
#include <sstream>
#include <string>
class myCout {
public:
std::stringstream ssOut; // Removing this gets rid of error
template <typename T> myCout& operator << (const T &x) {
// Do some formatting
return *this;
}
};
class myErr : public myCout {
public:
using myCout::operator<<;
};
int main(int argc, const char* argv[]) {
throw myErr() << "ErrorMsg" << 1;
myCout() << "Message Will Be Formatted";
return 0;
}
在编译时,会产生此错误:
1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\sstream(724): error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\ios(176) : see declaration of 'std::basic_ios<_Elem,_Traits>::basic_ios'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>
1> ]
1> This diagnostic occurred in the compiler generated function 'std::basic_stringstream<_Elem,_Traits,_Alloc>::basic_stringstream(const std::basic_stringstream<_Elem,_Traits,_Alloc> &)'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Alloc=std::allocator<char>
1> ]
(实际上它更复杂并扩展了类似的东西std::runtime_error
)
我已经看到了以前的答案,其中指出问题是由于没有通过引用传递流而引起的,但我看不出我是怎么做到的。
注释掉std::stringstream ssOut
修复的问题。为什么,以及如何解决根本问题?