【发布时间】:2016-12-28 19:44:12
【问题描述】:
我最近进入了 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 从protected: 转换为class a 的public: 成员。但这也给了我一个错误:
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;
^
现在我无法进行进一步的修改。我很想知道原始代码是否不会篡改类的受保护特性。
【问题讨论】:
-
&a<type>::b是形成指向成员的指针的特殊语法。您可以使用&(a<type>::b)组成一个简单的指针。 -
@iammilind Everything looks fine 添加括号后。
-
@Quentin,是的,我的立场是正确的。不过我觉得直接换成
(this->b),解决问题更勤快。对于这个特定的问题,链接的副本中没有答案。我再次关闭了这个问题。不确定,是否应该删除针对特定问题的答案。因此,通过给予怀疑的好处来保留它。
标签: c++ class templates pointers inheritance