C++错误处理(不知错哪了)
C++异常处理(不知哪里错了)
/////safearray.h
#include <stdexcpt.h>
#include <iostream>
using namespace std;
#ifndef SAFEARRAY_H
#define SAFEARRAY_H
template <typename T>
class safearray {
private:
T *storage;
int capacity;
public:
safearray() : storage(NULL), capacity(0) {} // default constructor
safearray(int); // single param constructor
~safearray(void); // destructor
T& operator[] (int) throw(std::out_of_range);
};
#endif
////safearray.cpp
#include <iostream>
#include "safearray.h"
template <typename T>
safearray<T>::safearray(int cap)
{
capacity = cap;
storage = new T[capacity];
}
template <typename T>
safearray<T>::~safearray(void)
{
delete []storage;
}
template <typename T>
T& safearray<T>::operator[] (int i) throw(std::out_of_range)
{
if(i < 0)
{
throw std::out_of_range("Index is below 0!");
}
else if(i > capacity)
{
throw std::out_of_range("Index is too high!");
}
return *(storage+i);
}
------解决方案--------------------
貌似是因为目前的编译器不支持模板的分离编译。建议楼主将类的声明和定义都在一个头文件里写,不要分开在头文件和cpp文件里。
------解决方案--------------------
写在了一个头文件中,编译无错误。。。
------解决方案--------------------
正解。
对于摸板来说,编译器对摸板的定义必须是可见的。
楼主的编译器应该是包含编译的。那楼主也可以将#include"safearray.cpp"加进类声明的头文件去。
/////safearray.h
#include <stdexcpt.h>
#include <iostream>
using namespace std;
#ifndef SAFEARRAY_H
#define SAFEARRAY_H
template <typename T>
class safearray {
private:
T *storage;
int capacity;
public:
safearray() : storage(NULL), capacity(0) {} // default constructor
safearray(int); // single param constructor
~safearray(void); // destructor
T& operator[] (int) throw(std::out_of_range);
};
#endif
////safearray.cpp
#include <iostream>
#include "safearray.h"
template <typename T>
safearray<T>::safearray(int cap)
{
capacity = cap;
storage = new T[capacity];
}
template <typename T>
safearray<T>::~safearray(void)
{
delete []storage;
}
template <typename T>
T& safearray<T>::operator[] (int i) throw(std::out_of_range)
{
if(i < 0)
{
throw std::out_of_range("Index is below 0!");
}
else if(i > capacity)
{
throw std::out_of_range("Index is too high!");
}
return *(storage+i);
}
c++
异常处理
------解决方案--------------------
貌似是因为目前的编译器不支持模板的分离编译。建议楼主将类的声明和定义都在一个头文件里写,不要分开在头文件和cpp文件里。
------解决方案--------------------
写在了一个头文件中,编译无错误。。。
------解决方案--------------------
正解。
对于摸板来说,编译器对摸板的定义必须是可见的。
楼主的编译器应该是包含编译的。那楼主也可以将#include"safearray.cpp"加进类声明的头文件去。