0

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

 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:只是我意识到错误实际上只在这里发音(这里链接到代码):

#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() {}

所以显然我把模板弄乱了。对不起,没有把它写在第一位。

4

2 回答 2

2

In a template, for unqualified names that refer to members inherited from a base class, you should use the explicit syntax by dereferencing this:

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

Or, alternatively, you could qualify the name this way:

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

Otherwise, the compiler will lookup name in the global namespace during the first phase of name lookup and, if not found, will issue an error.

于 2013-03-30T12:56:39.223 回答
0

除了缺少分号,代码很好。

唯一可能的解释是Class1,如编译器所见,实际上并没有该name成员。你有多个班级Class1吗?您是否有声明的头文件的多个副本Class1?您是否有可能在运行编译器之前忘记保存文件?

于 2013-03-30T11:11:39.887 回答