【问题标题】:How to access the address of base class member in inherited class member functions? [duplicate]如何在继承的类成员函数中访问基类成员的地址? [复制]
【发布时间】: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 = &amp;a&lt;type&gt;::b; 转换为type* a&lt;type&gt;::* q = &amp;a&lt;type&gt;::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;
             ^

所以我将bprotected: 转换为class apublic: 成员。但这也给了我一个错误:

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;
             ^

现在我无法进行进一步的修改。我很想知道原始代码是否不会篡改类的受保护特性。

【问题讨论】:

  • &amp;a&lt;type&gt;::b 是形成指向成员的指针的特殊语法。您可以使用&amp;(a&lt;type&gt;::b) 组成一个简单的指针。
  • @iammilind Everything looks fine 添加括号后。
  • @Quentin,是的,我的立场是正确的。不过我觉得直接换成(this-&gt;b),解决问题更勤快。对于这个特定的问题,链接的副本中没有答案。我再次关闭了这个问题。不确定,是否应该删除针对特定问题的答案。因此,通过给予怀疑的好处来保留它。

标签: c++ class templates pointers inheritance


【解决方案1】:

如果您在代码中更改以下行,您仍然可以使用 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>::*

虽然您可能想要&amp;(a&lt;type&gt;::b),但这会导致简单的int*
因此,它是笔记本示例之一,展示了将括号放在正确位置的好处! :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    相关资源
    最近更新 更多