|| c++ 中用于矢量范数的运算符

|| operator in c++ for vector norm

我正在尝试为向量编写自己的 "library",我可以在其中定义 运算符 ,例如 "*"用于标量乘法和 "+"+" 用于向量加法等。我想我大部分都是正确的,但现在我正在尝试使用 "| |",意思是:

Vector v;
// let v be (3, 4)
double a = |v|;
// then a should be 5 (sqrt(16 + 9))

但是我得到这个错误:

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|;

现在我正在努力定义运算符 ||...

我试过这样做:

double Vector::operator||(int){
//  here I used the scalar product to calculate the norm
    double d = (*this) * (*this);
    return sqrt(d);
}

或者我尝试将其定义为具有两个参数的友元函数。我认为主要问题是我必须给运算符什么参数,因为它总是需要两个(如果它是一个成员函数,则需要一个)。我就是想不出办法...

你们有没有人知道如何解决这个问题,或者没有解决方案,我必须使用正常的功能?

提前致谢:)

你不能这样做,因为 C++ 不支持这样的语法。您能做的最好的事情就是创建一个名为 magnitude 之类的函数并在其中进行计算。像这样:

template <typename T>
T magnitude(std::vector<T> const& vec) { ... }

double a = magnitude(v);

不管你怎么滥用C++的语法,恐怕都没有办法把double a = |v|;变成有效的代码,因为|只能是二元中缀运算符。