Ich versuche, mich mit Operatoren in C++ vertraut zu machen. Ich dachte, ich würde das mit einem einfachen Fall der Vektoraddition tun. Leider scheine ich auf einige Probleme gestoßen zu sein. Meine Klassendefinition lautet wie folgt:
#ifndef _MVEC_H_
#define _MVEC_H_
#include "Error.h" //Ich definiere Dinge wie throw(message) hier, es funktioniert und ist nicht das Problem
class MVec {
private:
double vec[3];
public:
MVec();
MVec(double &);
MVec(double *);
MVec(MVec &);
MVec & operator=(MVec &);
inline double & operator[](const int i);
inline const double & operator[](const int i) const;
MVec operator+(const MVec &) const;
~MVec();
};
MVec::MVec() {}
MVec::MVec(double &a) {
for(int i = 0; i < 3; i++)
vec[i] = a;
}
MVec::MVec(double *a) {
for(int i = 0; i < 3; i++)
vec[i] = *a++;
}
MVec::MVec(MVec &rhs) {
for(int i = 0; i < 3; i++)
vec[i] = rhs[i];
}
MVec & MVec::operator=(MVec &rhs) {
if(this != &rhs)
for(int i = 0; i < 3; i++)
vec[i] = rhs[i];
return *this;
}
inline double & MVec::operator[](const int i) {
#ifdef _CHECKBOUNDS_
if(i < 0 || i >= 3)
throw("Subscript out of bounds");
#endif
return vec[i];
}
inline const double & MVec::operator[](const int i) const {
#ifdef _CHECKBOUNDS_
if(i < 0 || i >= 3)
throw("Subscript out of bounds");
#endif
return vec[i];
}
MVec MVec::operator+(const MVec &vec1) const {
MVec ans;
for(int i = 0; i < 3; i++)
ans[i] = vec[i] + vec1[i];
return ans;
}
MVec::~MVec() {
delete[] vec;
}
#endif
Der [] Operator scheint wie beabsichtigt zu funktionieren. Leider funktioniert der Vektoradditionsoperator nicht. Speziell, wenn ich den Code ausführe:
#include "Error.h"
#include "MVec.h"
#include
#include
int main(int argc, char *argv[]) {
MVec a, b, c;
a[0] = 1; a[1] = 2; a[2] = 3;
b[0] = 5.9906; b[1] = 72.1139; b[2] = 83.1324;
//c = a + b;
std::cout << (a + b)[0] << std::endl;
std::cout << (a + b)[1] << std::endl;
std::cout << (a + b)[2] << std::endl;
exit(0);
}
Wenn ich die Zeile c = a + b; auskommentiere, erhalte ich einen Compilerfehler:
no match for 'operator=' in 'c = MVec::operator+(const MVec&) const(((const MVec&)((const MVec*)(& b))))'
Wenn ich es auskommentiere, erhalte ich nach dem ersten std::cout einen glibc detected Fehler. Vermutlich mache ich etwas falsch mit der temporären Variable, die ich in der operator+ Funktion erstelle. Leider bin ich nicht (ganz) schlau genug, um herauszufinden, was. Jeder Einblick dazu wäre sehr hilfreich.