假设我有这段代码:
class foo{
protected:
int a;
};
class bar : public foo {
public:
void copy_a_from_foo(foo& o){
a = o.a; // Error
}
void copy_a_from_bar(bar& o){
a = o.a; // OK
}
};
int main(){
bar x;
foo y;
bar z;
x.copy_a_from_foo(y);
x.copy_a_from_bar(z);
}
Run Code Online (Sandbox Code Playgroud)
这里class bar有没有问题访问受保护的成员a来自同一类的其他实例,但是当我尝试做同样与基类的一个实例foo,编译器给我的错误,说a是受保护的.标准对此有何看法?
错误是
prog.cpp: In member function 'void bar::copy_a_from_foo(foo&)':
prog.cpp:3:7: error: 'int foo::a' is protected
int a;
^
prog.cpp:9:11: error: within this context
a = o.a;
Run Code Online (Sandbox Code Playgroud)
PS:我看过这个问题 …
似乎来自模板策略类的受保护成员是不可访问的,即使类层次结构似乎是正确的.
例如,使用以下代码段:
#include <iostream>
using namespace std;
template <class T>
class A {
protected:
T value;
T getValue() { return value; }
public:
A(T value) { this->value = value; }
};
template <class T, template <class U> class A>
class B : protected A<T> {
public:
B() : A<T>(0) { /* Fake value */ }
void print(A<T>& input) {
cout << input.getValue() << endl;
}
};
int main(int argc, char *argv[]) {
B<int, A> b;
A<int> a(42);
b.print(a);
}
Run Code Online (Sandbox Code Playgroud)
编译器(OS …
这是代码:
class TestA
{
protected:
int test=12;
public:
TestA() {
cout << "test a: " << test << endl;
}
~TestA() {
}
};
class TestB : public TestA
{
public:
TestB(TestA *testA) {
cout << "test b: " << testA->test;
}
~TestB() {
}
};
int main ()
{
TestA *pTestA=new TestA();
TestB *pTestB=new TestB(pTestA);
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试protected使用指向TestA类型对象的指针(因此,实例TestA)来访问成员.TestB也来源于TestA
为什么我无法访问它?它只能在我需要它的类中"访问"吗?不在外面使用指针/直接声明?