gpt4 book ai didi

c++ - C++重新定义错误,为什么会出现此错误?

转载 作者:行者123 更新时间:2023-12-02 11:07:59 25 4
gpt4 key购买 nike

我有一个重新定义的问题,但是我注意到我已经在.hpp文件中包括了.cpp文件,所以我的错误是再次在.cpp文件中包括了.hpp文件
现在,我收到此错误,这与模板有关。
同样,当您解决我的问题时,能否向我解释什么是模板类?
cplusplus.com并不是那么描述。
谢谢。 :)

//implementation
template<class T>
ArrayBag<T>::ArrayBag() : item_count_(0){}

-------------警告您现在正在离开实现---------------------------
//interface
#ifndef ARRAY_BAG_H
#define ARRAY_BAG_H
#include <vector>

template<class T>
class ArrayBag
{
protected:
static const int DEFAULT_CAPACITY = 200;
T items_[DEFAULT_CAPACITY];
int item_count_;
int get_index_of_(const T& target) const;
public:
ArrayBag();
int getCurrentSize() const;
bool isEmpty() const;
//adds a new element to the end, returns true if it was successfully been added
bool add(const T& new_entry);
bool remove(const T& an_entry);
void clear();
bool contains(const T& an_entry) const;
int getFrequencyOf(const T& an_entry) const;
std::vector<T> toVector() const;
void display() const;
//overloading operators for objects
void operator+=(const ArrayBag<T>& a_bag);
void operator-=(const ArrayBag<T>& a_bag);
void operator/=(const ArrayBag<T>& a_bag);
};

#include "ArrayBag.cpp"
#endif

-------------警告您现在正在离开界面---------------------------
//error
5 C:\Users\minahnoona\Desktop\ArrayBag.cpp expected constructor, destructor, or type conversion before '<' token
5 C:\Users\minahnoona\Desktop\ArrayBag.cpp expected `;' before '<' token

最佳答案

不要将ArrayBag.cpp称为.cpp文件。模板实现放在头文件中,名称应反射(reflect)出来。

如果要在单独的文件中实现(严格不需要),请将其称为ipptpp。项目系统中的某些内容不会尝试自行编译。

然后从.hpp包含它,而不从.hpp包含.ipp

关于c++ - C++重新定义错误,为什么会出现此错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58041475/

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