C++ C++;具有类成员的模板类
我在模板方面没有太多经验,但我正在努力学习,所以有人能告诉我我该怎么做才能使这项工作正常进行,因为我见过很多使用类型名、显式实例化和显式专门化的示例,但它们只包括基本类型,如int、char、,。。。 所以请帮忙,因为我不知道该怎么办 容器.hC++ C++;具有类成员的模板类,c++,class,templates,C++,Class,Templates,我在模板方面没有太多经验,但我正在努力学习,所以有人能告诉我我该怎么做才能使这项工作正常进行,因为我见过很多使用类型名、显式实例化和显式专门化的示例,但它们只包括基本类型,如int、char、,。。。 所以请帮忙,因为我不知道该怎么办 容器.h #ifndef CONTAINER_H #define CONTAINER_H template <typename E> class Container { private: E element; publ
#ifndef CONTAINER_H
#define CONTAINER_H
template <typename E>
class Container
{
private:
E element;
public:
Container(E pElement);
virtual ~Container();
};
#endif // CONTAINER_H
我得到的错误是:
src\Container.cpp|7|error: no matching function for call to 'Piece::Piece()'|
src\Container.cpp|7|note: candidates are:|
src\Piece.cpp|3|note: Piece::Piece(int, int, std::string)|
src\Piece.cpp|3|note: candidate expects 3 arguments, 0 provided|
include\Piece.h|8|note: Piece::Piece(const Piece&)|
include\Piece.h|8|note: Piece::Piece(const Piece&)|
我不知道我应该在那里做些什么来让事情顺利进行。请提供帮助。您已经为
工件
提供了一个显式构造函数,即
Piece::Piece(int, int, std::string)
所以构造函数并没有向您提供默认构造函数。现在在容器中
使用的是无参数构造函数。这就是错误的原因。
因此,您需要为片段
提供一个无参数(默认)构造函数。
现在如果
是错误消息。然后在头文件中定义了它。但在源文件(或其他地方)中并没有主体。所以链接器找不到它。因此,还要向构造函数添加一个主体。如果在构造函数的初始化列表中初始化成员,则不必提供默认构造函数:
template <typename E>
Container<E>::Container(E pElement) : element(pElement)
{
}
模板
容器::容器(E pElement):元素(pElement)
{
}
在代码中,您初始化了构造函数主体内的成员,因此这意味着
元素
应该首先由默认构造函数构造,然后由赋值运算符修改。因为您没有为片段提供默认构造函数,这就产生了一个错误。如果您要使用它,当然不要使用命名空间std放置代码>在头文件中。添加工件的默认构造函数(添加新构造函数或将变量的默认值添加到现有构造函数)。另外,您似乎忘记了destructor实现,因为@jonezq声明您需要添加默认构造函数,请参阅。这是因为您还需要一个析构函数体。仅仅在页眉中定义是行不通的。因为链接器找不到执行函数的代码,所以调用了函数。如果要显式定义函数并在别处调用它。你需要一个身体。
src\Container.cpp|7|error: no matching function for call to 'Piece::Piece()'|
src\Container.cpp|7|note: candidates are:|
src\Piece.cpp|3|note: Piece::Piece(int, int, std::string)|
src\Piece.cpp|3|note: candidate expects 3 arguments, 0 provided|
include\Piece.h|8|note: Piece::Piece(const Piece&)|
include\Piece.h|8|note: Piece::Piece(const Piece&)|
Piece::Piece(int, int, std::string)
src\Container.cpp|7|undefined reference to `Piece::Piece()'
template <typename E>
Container<E>::Container(E pElement) : element(pElement)
{
}