私はC++の演算子に慣れようとしています。ベクトル加算の単純なケースでそうするだろうと思いました。残念ながら、私はいくつかの問題に遭遇したようです。私のクラス定義は次のとおりです。
#ifndef _MVEC_H_
#define _MVEC_H_
#include "Error.h" //I define things like throw(message) here, it works and is not the issue
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
[]演算子は意図したとおりに機能しているようです。残念ながら、ベクトル加算演算子はそうではありません。具体的には、コードを実行すると次のようになります。
#include "Error.h"
#include "MVec.h"
#include <cstdlib>
#include <iostream>
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);
}
行のコメントを外すと、c = a + b; コンパイラエラーが発生します:
'c = MVec :: operator +(const MVec&)const(((const MVec&)((const MVec *)(&b))))'の'operator='に一致しません
コメントアウトすると、最初のstd::coutの後にglibcが検出したエラーが発生します。おそらく、operator+関数で作成している一時変数で何か問題が発生しています。残念ながら、私は(かなり)賢くなく、何を理解することができません。これに関するありとあらゆる洞察は非常に役立ちます。