【问题标题】:Inheritance and template in C++: Why doesn't the following piece of code compile?C++中的继承和模板:为什么下面这段代码不能编译?
【发布时间】:2015-04-26 10:30:32
【问题描述】:

我有一个简单的 c++ 程序,但我无法编译,虽然我尝试在谷歌中搜索并尝试阅读有关模板、继承和向量的信息,但我不知道我在做什么错误, 谁能帮帮我吗!! 以下是代码:

template <class T>
class Base
{
  public:
  int entries;
};
template <class T>
class Derive : public Base<T *>
{
  public:
  int j;
  void pankaj(){j = entries;}
  void clear();

};
template <class T> void Derive<T>::clear()
{
  int i;
  int j=entries;
};
int main()
{
  Derive b1;
}

我收到以下错误: pankajkk> g++ sample.cpp

sample.cpp: In member function 'void Derive<T>::pankaj()':
sample.cpp:14: error: 'entries' was not declared in this scope
sample.cpp: In member function 'void Derive<T>::clear()':
sample.cpp:22: error: 'entries' was not declared in this scope
sample.cpp: In function 'int main()':
sample.cpp:26: error: missing template arguments before 'b1'
sample.cpp:26: error: expected `;' before 'b1'

谢谢!!

【问题讨论】:

  • 这些空白是怎么回事?
  • 删除了多余的空格。
  • @KarolyHorvath 确实有效,但为什么没有this-&gt; 就不能工作? FWIW Base&lt;T*&gt;::entries 也可以。
  • @KarolyHorvath 在将条目更改为 this-> 条目后它起作用了。非常感谢:)

标签: c++ templates c++11 inheritance g++


【解决方案1】:

您必须使用this-&gt;foo 访问模板基类中的成员变量fooYou may ask why.

另外,正如 Old Fox 所解释的,在声明变量 b1 时必须指定类型 T

template <class T>
class Base
{
  public:
  int entries;
};

template <class T>
class Derive : public Base<T *>
{
  public:
  int j;
  void pankaj(){j = this->entries;}
  void clear();
};

template <class T> void Derive<T>::clear()
{
  int i;
  int j=this->entries;
};

int main()
{
  Derive<int> b1;
}

live demo here

【讨论】:

    【解决方案2】:

    你的main方法有语法错误,改成:

    int main()
    {
        Derive<int> b1;
    }
    

    你可以放其他类型而不是整数...

    在 C++ 中的模板是 compile time

    【讨论】:

    • @cmbasnett ,我把他的代码带进了visual studio,修改后编译没有任何错误
    • 不幸的是,这并不意味着代码是正确的......责备VS。
    • @Old Fox - 很公平,我也使用 VS,但看起来 VS 不符合 C++ 标准,根据 OP 中 cmets 中的链接。
    • @OldFox 它修复了第 1 行的编译器错误。 26,但我仍然收到其他错误。
    • @OldFox 我正在使用 g++ 4.9 进行编译。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 2010-10-24
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多