我最近在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:
的{{1}}成员class a
。但这也给了我一个错误:
protected:
现在我无法进行进一步的修改。我很想知道原始代码是否不会篡改班级受保护的特征。
答案 0 :(得分:2)
如果您在代码中更改以下行,则仍然可以使用protected: type *b;
:
type **q = &a<type>::b; // `protected: b` is not accessible in this context
到
type **q = &(this->b); // we make sure that `protected: b` is accessed here
在这种情况下,您实际上将b
视为继承的protected
成员。
为什么要使用this
来访问基类?
参考:In a templated derived class, why do I need to qualify base class member names with "this->" inside a member function?
另一种方式
最初由@Quentin链接,下面的帖子暗示了简单指针和指向成员的指针之间的区别:
Pointer-to-member confusion
因此,在您的原始问题中,您实际上是通过以下语法尝试获取指向成员变量的指针:
&a<type>::b ==> int* a<int>::*
虽然你可能想要&(a<type>::b)
,这会导致简单的int*
所以它是笔记本电脑的一个例子,展示了将括号放在正确位置的好处! : - )