c++ - 从子构造函数(模板)访问父成员

标签 c++ oop templates

<分区>

所以我有一些简单的问题/结构:

 class Class1 {
   public:
      Class1() {};
      ~Class1() {};
   protected:
      std::string name;
 }

 class Class2 : public Class1
 {
   public:
     Class2() : number(id_generator++) {
       name = "My-name"; // (1) want to access field inherited from Parent
   };

   private:
      const unsigned int number;
      static unsigned int id_generator;
  }

编译器提示 (1):'name' was not declared in this scope。怎么了?它看起来很简单,但我没有看到。

EDIT1:我才意识到错误实际上只在这里出现(here 链接到代码):

#include <string>

template<int dim>
class Class1 {
   public:
      Class1() {};
     ~Class1() {};
   protected:
      std::string name;
 };

template<int dim>
class Class2 : public Class1<dim>
{
   public:
     Class2() : number(id_generator++) {
       name = "My-name"; // (1) want to access field inherited from Parent
     };

   private:
     const unsigned int number;
     static unsigned int id_generator;
};

int main() {}

很明显我把模板搞砸了。抱歉,没有把它写在第一位。

最佳答案

在模板中,对于引用从基类继承的成员的非限定名称,您应该通过取消引用 this 来使用显式语法:

 Class2() : number(id_generator++) {
     this->name = "My-name"; // (1) want to access field inherited from Parent
 //  ^^^^^^
 };

或者,您可以这样限定名称:

 Class2() : number(id_generator++) {
     Class1<dim>::name = "My-name";
 //  ^^^^^^^^^^^^^
 };

否则,编译器将在 first phase of name lookup 期间在全局命名空间中查找 name并且,如果未找到,将发出错误消息。

关于c++ - 从子构造函数(模板)访问父成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15717833/

相关文章:

c++ - QString::split() 和 "\r"、 "\n"和 "\r\n"约定

c++ - 将带有模板参数的方法传递给宏

C++ : Scope of struct inside a class

c - C语言中的多态应用问题

database - 库存系统的设计决策

c++ - C++ 编译器中的奇怪行为 - 优化?

Android NDK GCC 似乎是 clang - 它应该是这样吗?

c++ - 为什么模板只能在头文件中实现?

templates - 为什么我的 Magento 产品页面的评论部分没有显示?

c++ - 函数指针的函数模板特化