【发布时间】:2016-03-24 06:20:35
【问题描述】:
我没有太多使用模板的经验,但我正在努力学习,所以有人可以告诉我我该怎么做才能完成这项工作,因为我已经看到了很多使用类型名的例子和显式实例化和显式特化,但它们只包括基本类型,如 int、char、... 所以请帮忙,因为我不明白该怎么做。
容器.h
#ifndef CONTAINER_H
#define CONTAINER_H
template <typename E>
class Container
{
private:
E element;
public:
Container(E pElement);
virtual ~Container();
};
#endif // CONTAINER_H
容器.cpp
#include "Container.h"
#include "Piece.h"
template class Container<Piece>;
template <typename E>
Container<E>::Container(E pElement) //Error Here;
{
element=pElement;
}
Piece.h
#ifndef PIECE_H
#define PIECE_H
#include <iostream>
#include <string>
using namespace std;
class Piece
{
private:
int x;
int y;
string z;
public:
Piece(int pX,int pY, string pZ);
virtual ~Piece();
};
#endif // PIECE_H
片段.cpp
#include "Piece.h"
Piece::Piece(int pX, int pY, string pZ){
x=pX;
y=pY;
z=pZ;
}
我得到的错误是:
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&)|
而且我不知道我应该在那里做什么才能让事情顺利进行。请帮忙。
【问题讨论】:
-
如果你要使用它,千万不要把
using namespace std;放在头文件中。 -
添加 Piece 的默认构造函数,(添加新构造函数或将变量的默认值添加到现有构造函数)。看起来你也忘记了析构函数的实现
-
正如@jonezq 所说,您需要添加一个默认构造函数,请参阅What are all the member-functions created by compiler for a class? Does that happen all the time?。