<分区>
我最近进入了 C++ 类、继承和模板的整个世界。但是我卡住了。请建议我解决此问题的方法。
#include <iostream>
using namespace std;
template <typename type>
class a
{
protected:
type *b;
};
template <typename type>
class p : public a<type>
{
public:
void f()
{
type **q = &a<type>::b;
cout << *q << endl; // some other code in reality related to (*q)
}
};
int main()
{
p<int> obj;
obj.f();
return 0;
}
但是结果不成功:
x.cpp: In instantiation of ‘void p<type>::f() [with type = int]’:
x.cpp:26:9: required from here
x.cpp:9:9: error: ‘int* a<int>::b’ is protected
type *b;
^
x.cpp:18:16: error: within this context
type **q = &a<type>::b;
^
x.cpp:18:26: error: cannot convert ‘int* a<int>::*’ to ‘int**’ in initialization
type **q = &a<type>::b;
^
所以我转换了type **q = &a<type>::b;
至 type* a<type>::* q = &a<type>::b;
.然后我得到了一个额外的错误:
x.cpp: In instantiation of ‘void p<type>::f() [with type = int]’:
x.cpp:26:9: required from here
x.cpp:9:9: error: ‘int* a<int>::b’ is protected
type *b;
^
x.cpp:18:26: error: within this context
type* a<type>::* q = &a<type>::b;
^
x.cpp:19:13: error: invalid use of unary ‘*’ on pointer to member
cout << *q;
^
所以我转换了b
到 public:
class a
的成员来自 protected:
.但这也给了我一个错误:
x.cpp: In instantiation of ‘void p<type>::f() [with type = int]’:
x.cpp:26:9: required from here
x.cpp:19:13: error: invalid use of unary ‘*’ on pointer to member
cout << *q;
^
现在我无法进行进一步的修改。我很想知道原始代码是否没有篡改类的 protected 特性。