gpt4 book ai didi

c++ - 字符串流错误 : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'

转载 作者:太空狗 更新时间:2023-10-29 20:27:24 27 4
gpt4 key购买 nike

在创建一个简单的异常类扩展(我可以在其中更轻松地构建错误消息)时,我将错误隔离为以下简单代码:

#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 之类的东西)

我看过previous answers哪个状态的问题是由于没有通过引用传递流而引起的,但我看不出我不是。

注释掉 std::stringstream ssOut 修复了这个问题。为什么以及如何解决根本问题?

最佳答案

您按值抛出异常,这确实是推荐的做法。然而,这意味着异常被复制为 throw 语句的一部分,因此它必须有一个可访问的复制构造函数。并且因为您有一个不可复制的成员 (std::stringstream),所以您必须提供自己的复制构造函数。

关于c++ - 字符串流错误 : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16515644/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com