c++ - 如何在继承类成员函数中访问基类成员的地址?

标签 c++ class templates pointers inheritance

<分区>

我最近进入了 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;
             ^

所以我转换了bpublic: 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 特性。

最佳答案

您仍然可以接受 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* .
所以这是笔记本示例之一,展示了将括号放在正确位置的好处! :-)

关于c++ - 如何在继承类成员函数中访问基类成员的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39076440/

相关文章:

java - 将高度模板化的 C++ 代码迁移到 Java

c++ - B-Tree中是否有批量加载的算法?

c++ - 从图像中去除小 Blob

c++ - 如何恢复基类指针指向的对象的原始类型?

c++ - 作为参数传递给函数模板时如何隐式转换类模板对象?

c++ - 对简单的 Arduino 类进行故障排除

c++ - 将 const 添加到引用

C++ API 设计 : Clearing up public interface

c++ - 静态库中的单例类

C# 泛型与 C++ 模板的比较