<分区>
看起来不可能通过 shared_ptr 访问 protected 成员。这是一个无法编译的最小示例:
// compile with g++ -std=c++11 protect.cpp
#include <iostream>
#include <memory>
class C
{
public:
C(int xval = 0) : x(xval) {}
protected:
int x = 0;
};
class D : public C
{
public:
D(int xval = 0) : C(xval) {}
void print_sum( const std::shared_ptr<C>& other );
};
void D::print_sum( const std::shared_ptr<C>& other )
{
int sum = x + other->x;
std::cout << "the sum is " << sum << std::endl;
}
int main( int argc, char** argv, char** envp)
{
std::shared_ptr<C> first = std::make_shared<C>(2);
std::shared_ptr<D> second = std::make_shared<D>(3);
second->print_sum( first );
return 0;
}
下面是我收到的具体错误消息:
$ g++ -std=c++11 protect.cpp
protect.cpp: In member function ‘void D::print_sum(const std::shared_ptr<C>&)’:
protect.cpp:13:15: error: ‘int C::x’ is protected
int x = 0;
^
protect.cpp:25:25: error: within this context
int sum = x + other->x;
虽然 D
派生自 C
,但 D
无法访问 x
似乎很奇怪,而且我一直认为派生类可以使用 protected
基类成员。
这个问题对我来说并不是真正的障碍;在我的用例中,C
和 D
将作为同一补丁集的一部分来实现,因此只需制作 x
就足够了public 作为解决方法。但是是否有更“惯用”的方式来使这段代码工作?
以防万一这是一个 gcc 错误,这里是我使用的版本:
$ cat /etc/issue
Ubuntu 14.04.3 LTS \n \l
$ g++ --version
g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.