Ich habe KlasseC++ wirft Ausnahme
template <class T>
class Box {
public:
Box() : size(2), count(0) {
arr = new T[size];
}
void add(T);
T operator[](int);
private:
int size;
int count;
T * arr;
};
operator [] Funktion
template <class T>
T Box<T>::operator[](int index) {
if (index >= count)
throw "Index out of bounds";
return arr[index];
}
In Hauptfunktion I zum Kasten unter Verwendung add
Funktion zuerst ein Element hinzuzufügen. Dann habe ich versucht, es durch box[0]
zu bekommen, und es funktioniert gut. Ich möchte, dass der Code eine Ausnahme auslöst, wenn ich versucht habe, box[1]
zu tun, da es kein zweites Element gibt. Aber statt eine Ausnahme zu werfen, gibt es mir diesen Fehler:
Exception thrown at 0x7701DAD8 in Project24.exe: Microsoft C++ exception: char at memory location 0x0018F8A8.
If there is a handler for this exception, the program may be safely continued.
Ich habe einen Ausnahmebehandler. Warum erhalte ich diesen Fehler?
EDIT: öffnete ich ein neues Projekt, kopiert alle Dateien und verändert die Funktion operator[]
als
template <class T>
T Box<T>::operator[](size_t index) {
string s("Index out of bounds");
if (index >= count)
throw s;
return arr[index];
}
Es funktioniert jetzt.
Sie sollten ein vollständiges, minimales und überprüfbares Beispiel erstellen. http://StackOverflow.com/Help/Mcve – user31264
Könnte das Problem sein, dass Sie ein const Char * werfen und dass es in Bezug auf Speicher nicht wirklich sicher ist? Versuchen Sie, stattdessen eine std :: string zu werfen – NoImaginationGuy
Führen Sie eine Debugsitzung im VS-Debugger aus? –