【问题标题】:C++ Template Class with Class Member具有类成员的 C++ 模板类
【发布时间】: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&)|

而且我不知道我应该在那里做什么才能让事情顺利进行。请帮忙。

【问题讨论】:

标签: c++ class templates


【解决方案1】:

如果在构造函数的初始化列表中初始化一个成员,那么就不必提供默认构造函数:

template <typename E>
Container<E>::Container(E pElement) : element(pElement)
{

}

在您的代码中,您在构造函数的主体内初始化了成员,因此这意味着 element 应该首先由默认构造函数构造,然后由赋值运算符修改。而且因为您没有为Piece 提供默认构造函数,所以会报错。

【讨论】:

    【解决方案2】:

    您已经为Piece 提供了一个显式构造函数,即

    Piece::Piece(int, int, std::string)
    

    所以构造函数没有为你提供默认构造函数。现在在Container 中,您正在使用无参数构造函数。这就是错误的原因。 所以你需要为Piece 提供一个无参数(默认)的构造函数。 现在如果

    src\Container.cpp|7|undefined reference to `Piece::Piece()'
    

    是错误消息。然后你在头文件中定义了它。但是源文件(或其他地方)中没有正文。所以链接器找不到它。因此,还要向构造函数添加一个主体。

    【讨论】:

    • 那是因为你还需要一个析构函数的主体。仅在标题中定义是行不通的。因为链接器不会找到执行该函数的代码。如果您明确定义一个函数并在其他地方调用它。你需要一个身体。
    猜你喜欢
    • 1970-01-01
    • 2013-05-11
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 2019-04-12
    • 2020-03-28
    相关资源
    最近更新 更多