gpt4 book ai didi

c++ - 模板类找不到构造函数

转载 作者:行者123 更新时间:2023-11-30 01:51:00 24 4
gpt4 key购买 nike

我目前正在研究模板类(我很迷茫)。我想构建一个可以存储对象的模板类。

这是我的 .h 文件:

#ifndef STORAGE_H_
#define STORAGE_H_

#include <iostream>
using namespace std;

template<class T,int maxsize>
class Storage
{
public:
Storage();

int getSize();
T get(int index);
bool add(T element);

private:
T array[maxsize];
int length;

};

template<class T,int maxsize>
Storage<T,maxsize>::Storage()
: length(0),// Liste d'initialisation des données membres
{}

template<class T,int maxsize>
int Storage<T,maxsize>::getSize()
{
return length;
}

template<class T,int maxsize>
T Storage<T,maxsize>::get(int index)
{
return array[index];
}

template<class T,int maxsize>
bool Storage<T,maxsize>::add(T element)
{
if (length>=maxsize) return false;
array[length++]=element;
return true;
}

#endif /* STORAGE_H_ */

例如,当我处理 int 时,它工作正常。但是当涉及到我之前制作的其他对象时,它失败了。在我的主 .cpp 文件中:

Storage<Pokemon,4> pokemonArray;

这会向我发送以下错误:

no matching function for call to 'Pokemon::Pokemon()'

口袋妖怪是我上的一门课。对我来说,这一行意味着它找不到构造函数 Pokemon()。

我怎样才能让它发挥作用?

谢谢大家!

最佳答案

假设 Pokemon 有一个默认的构造函数,下面的代码可以工作:

#include <iostream>
using namespace std;

template<class T,int maxsize>
class Storage
{
public:
Storage();

int getSize();
T get(int index);
bool add(T element);

private:
T array[maxsize];
int length;

};

template<class T,int maxsize>
Storage<T,maxsize>::Storage()
: length(0)
{}

template<class T,int maxsize>
int Storage<T,maxsize>::getSize()
{
return length;
}

template<class T,int maxsize>
T Storage<T,maxsize>::get(int index)
{
return array[index];
}

template<class T,int maxsize>
bool Storage<T,maxsize>::add(T element)
{
if (length>=maxsize) return false;
array[length++]=element;
return true;
}

class Pokemon{

public: Pokemon(){};
};

int main(){
Storage<Pokemon,4> pokemonArray;
}

请注意,如果没有给出构造函数,编译器会自动生成一个并且代码仍然可以编译。

class Pokemon{
//no constructors is still ok
};

默认构造函数由存储类中的 Array 隐式调用。您的 Pokemon 类中很可能有一个非平凡的构造函数导致了问题。也许是这样的:

class Pokemon{

public:
Pokemon(std::string name){
//....
}
//...
};

当你提供一个非平凡的构造函数时,编译器不会隐式添加一个,因此,你要么需要更改你的 Storage 类,要么为 Pokemon 类提供一个默认构造函数以及你当前的构造函数:

class Pokemon{

public:
Pokemon(){}; //<-- needed
Pokemon(std::string name){ ... }; //<-- optional
};

关于c++ - 模板类找不到构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26721479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com