模板继承

con*_*ist 0 c++ inheritance templates constructor

我有一个C++类模板和另一个继承它的类.正如您将看到的,后者不是类模板.当我尝试通过调用基类的构造函数(模板一)来定义派生类的构造函数时,会出现问题.我在代码下面发布了错误.

为简单起见,我只添加了声明.如果你觉得代码可以帮助你了解问题可能是什么,我会很乐意发布它.

state2d.h

#ifndef STATE2D_H
#define STATE2D_H

template <typename T>
class State2D
{
public:
    State2D(unsigned int _rows, unsigned int _columns);
    State2D(unsigned int _rows, unsigned int _columns, const T& val);
    State2D(const State2D<T> &st);
    ~State2D();
    T& operator()(unsigned int i, unsigned int j);
    const T& operator()(unsigned int i, unsigned int j) const;
    unsigned int GetRowCount() const;
    unsigned int GetColumnCount() const;
    unsigned int GetAvailablePositionsCount() const;

protected:
    T** matrix;
    unsigned int rows;
    unsigned int columns;
    unsigned int availablePositions;
};

#endif // STATE2D_H
Run Code Online (Sandbox Code Playgroud)

TicTacToeState.h

#ifndef TICTACTOESTATE_H
#define TICTACTOESTATE_H

#include "state2d.h"

class TicTacToeState : public State2D<char>
{
public:
    TicTacToeState();
};

#endif // TICTACTOESTATE_H
Run Code Online (Sandbox Code Playgroud)

TicTacToeState.cpp

#include "tictactoestate.h"

TicTacToeState::TicTacToeState() : State2D(3,3,' ') // ERROR here; see below
{
}
Run Code Online (Sandbox Code Playgroud)

错误:类'TicTacToeState'没有任何名为'State2D'的字段错误:对'State2D :: State2D()'候选者的调用没有匹配函数:State2D :: State2D(const State2D&)[with T = char] State2D: :State2D(unsigned int,unsigned int,const T&)[with T = char] State2D :: State2D(unsigned int,unsigned int)[with T = char]

有任何想法吗?

Mic*_*ker 10

: State2D<char>(3,3,' ')
Run Code Online (Sandbox Code Playgroud)

也许?

  • @conectionist:现在是时候挖掘10亿个重复项中的任何一个[为什么模板定义需要进入标题](http://stackoverflow.com/questions/3749099/why-should-the-implementation-and-the -declaration-of-a-template-class-in-the)...(另见该问题中的"链接"列) (10认同)
  • 这是一个微不足道的问题,有一个简单的答案:接受它! (3认同)