我正在实现一个 C++ 应用程序,除此之外,我还使用 Poco 库。具体来说,我正在尝试使用 poco 日志记录框架。我创建了一个类,该类使用来自一个 poco 示例的以下代码来创建日志记录机制:
AutoPtr<PatternFormatter> pPatternFormatter(new PatternFormatter());
AutoPtr<FormattingChannel>pFormattingChannel(new
FormattingChannel(pPatternFormatter));
pPatternFormatter->setProperty("pattern", "%s: %p : %t");
AutoPtr<ConsoleChannel> pConsoleChannel(new ConsoleChannel());
pFormattingChannel->setChannel(pConsoleChannel);
然而,当我试图用 poco SharedPtr 指针替换 poco AutoPtr 时 我收到以下构建错误:
错误 C2248“Poco::FileChannel::~FileChannel”:无法访问类“Poco::FileChannel”中声明的 protected 成员
我已经搜索并发现 FileChannel 类的析构函数受到保护,我认为使用它是为了防止通过指向其基类的指针删除对象。 使我的类派生自具有公共(public)或 protected 访问说明符的 FileChannel 以使 SharedPtr 工作或以其他方式工作是否有效?
最佳答案
出于好奇,我想到了:如果派生类将析构函数简单地公开怎么办?实际上,这听起来太简单了,但我相信它应该可行。
示例test-prot-dtor.cc
:
#include <iostream>
class Base {
public:
Base() { std::cout << "Base::Base()" << std::endl; }
protected:
virtual ~Base() { std::cout << "Base::~Base()" << std::endl; }
};
class Derived: public Base {
public:
Derived() { std::cout << "Derived::Derived()" << std::endl; }
virtual ~Derived() { std::cout << "Derived::~Derived()" << std::endl; }
};
int main()
{
#if 0 // Does not work!
Base *pBase = new Derived;
delete pBase;
/* here:
* error: 'virtual Base::~Base()' is protected
*/
#endif // 0
Derived *pDerived = new Derived;
delete pDerived;
// done
return 0;
}
在 Windows 10(64 位)上使用 VisualStudio 2013 (Express) 和 cygwin 中的 gcc 进行测试。下面是与后者的示例 session :
$ g++ --version
g++ (GCC) 5.4.0
$ g++ -std=c++11 -c test-prot-dtor.cc
$ ./test-prot-dtor
Base::Base()
Derived::Derived()
Derived::~Derived()
Base::~Base()
$
关于你的想法(让 SharedPtr
成为你的派生类的 friend )我不确定。这取决于 SharedPtr
的实现细节,即它是“自己完成工作”还是将其委托(delegate)给另一个(最终甚至隐藏的)类/方法或函数...
关于c++ - 绕过错误 C2248 "cannot access protected member declared in class"的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43588475/