我定义了Bag类的构造函数,但是编译器给我定义一个错误。我在Mac上使用CLion。我不知道怎么了。我认为这可能与CLion或编译器问题有关。任何帮助,将不胜感激!
这是来自编译器的错误消息
/Users/username/Desktop/projects/bag/Bag.cpp:8:1: error: 'Bag' is not a class, namespace, or enumeration
Bag::Bag() : data{new T[CAPACITY]}, size{0} {}
^
/Users/username/Desktop/projects/bag/Bag.h:15:7: note: 'Bag' declared here
class Bag{
这里是'Bag.h'文件中的Bag类的声明。
#ifndef BAG_BAG_H
#define BAG_BAG_H
#include <vector>
#include <cstdlib>
using namespace std;
static const size_t CAPACITY = 100;
template <class T>
class Bag{
public:
Bag();
size_t size() const;
bool empty();
bool check(const T& item);
void resize(size_t new_size);
void clear();
void remove(const T& item);
void add(T item);
void print();
private:
T* data;
size_t _size;
};
#endif //BAG_BAG_H
这里是'Bag.cpp'文件中的Bag类的定义。
#include "Bag.h"
template <class T>
Bag::Bag() : data{new T[CAPACITY]}, size{0} {}
... other definitions
这里是main.cpp
#include <iostream>
#include "Bag.h"
int main() {
Bag<int> temp();
temp().add(1);
temp().print();
cout << endl;
return 0;
}
您有一个模板类。所以你必须写
template <class T>
Bag<T>::Bag() : data{new T[CAPACITY]}, size{0} {}