我在模板方面没有太多经验,但我正在努力学习,所以有人可以告诉我我该怎么做才能完成这项工作,因为我已经看到了很多使用类型名的例子和显式实例化和显式特化,但它们只包括基本类型,如 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;
}
片.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&)|
而且我不知道我应该在那里做什么才能使事情正常进行。请帮忙。
最佳答案
如果在构造函数中初始化初始化列表中的成员,则不必提供默认构造函数:
template <typename E>
Container<E>::Container(E pElement) : element(pElement)
{
}
在您的代码中,您在构造函数体内初始化了成员,因此这意味着 element
应该首先由默认构造函数构造,然后由赋值运算符修改。因为您没有为 Piece
提供默认构造函数,所以这会出错。
关于具有类成员的 C++ 模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36194319/