I'm trying to write a own "library" for vectors where I can define operators such as "*" for scalar multiplication and "+" for vector addition etc. I think I got most of it right, but now I'm trying to define a operator for the l2 norm of a vector using "| |", meaning this:
Vector v;
// let v be (3, 4)
double a = |v|;
// then a should be 5 (sqrt(16 + 9))
but then I get this error:
main.cpp:11:17: error: no match for 'operator|' (operand types are 'Vector' and 'int')
double a = v|2|;
~^~
main.cpp:11:20: error: expected primary-expression before ';' token
double a = v|2|;
Now here I'm struggling to define the operator ||...
I tried doing something like this:
double Vector::operator||(int){
// here I used the scalar product to calculate the norm
double d = (*this) * (*this);
return sqrt(d);
}
or I tried defining it as friend function with two parameters. I think the main problem is what parameters I have to give the operator because it always requiers two (or one if its a member function). I just cant figure out a way to do it...
Has anyone of you an idea how solve this or is there no solution for this and I have to use a normal function?
Thanks in advance :)
You can't do that, because C++ doesn't support such a syntax. The best you can do is to create a function called something like magnitude
and do your calculations in it. Like this:
template <typename T>
T magnitude(std::vector<T> const& vec) { ... }
double a = magnitude(v);