我读到一个声明为成员函数的重载运算符是非对称的,因为它只能有一个参数而另一个自动传递的参数是this指针.所以没有比较它们的标准.另一方面,声明为a的重载运算符friend是对称的,因为我们传递两个相同类型的参数,因此可以对它们进行比较.
我的问题是,当我仍然可以将指针的左值与参考值进行比较时,为什么会选择朋友?(使用非对称版本提供与对称相同的结果)为什么STL算法仅使用对称版本?
c++ operator-overloading member-functions friend-function non-member-functions
我是新手重载运算符,我做了一些搜索,发现这篇有用的文章,我写了自己的代码,就像作者一样,但我得到了vector vector::operator*(float, vector) must take either zero or one argument错误.
这是我的代码:
class vector
{
public:
float x;
float y;
vector(float, float);
float operator$ (vector, vector);
vector operator* (float, vector);
vector operator* (vector, float);
};
vector::vector(float _x = 0, float _y = 0)
{
x = _x;
y = _y;
}
const float vector::operator$ (const vector &v1, const vector &v2)
{
return (v1.x * v2.x) + (v1.y * v2.y);
}
const vector vector::operator* (const float &m, const …Run Code Online (Sandbox Code Playgroud) 请原谅,但我不知道在短时间内给这个标题命名.
为什么我需要在标头中声明一个重载的运算符,以使其在此示例中起作用:
HEAD.H
#pragma once
namespace test {
class A {
public:
A() : x(0) {}
int x;
};
A& operator++(A& obj); //this is my question
}
Run Code Online (Sandbox Code Playgroud)
HEAD.CPP
#include "head.h"
namespace test {
A& operator++(A& obj) {
++obj.x;
return obj;
}
}
Run Code Online (Sandbox Code Playgroud)
main.cpp中
#include <iostream>
#include "head.h"
using namespace std;
using namespace test;
int main() {
A object;
++object; //this won't work if we delete declaration in a header
return 0;
}
Run Code Online (Sandbox Code Playgroud)
operator ++是在"head.cpp"中的命名空间中定义和声明的,那么为什么我需要在头文件中再次声明它呢?谢谢.