我是 C++ 新手,但我有很好的编程背景,而且我一直在寻找不需要结构或类的引用对象的函数调用。我正在寻找的最佳参考可能是任何统一的类,例如可以使用 Vector2.Distance 并且它返回另一个 Vector2 但 Vector2 是类!
#include <stdio.h>
#include <stdlib.h>
struct vector {
float x, y;
// only recently figured out you could do this
// instead of vector() {x = 0.0; y = 0.0} etc.
vector() : x(0.0), y(0.0) {}
vector(float _x, float _y) : x(_x), y(_y) {}
vector add(vector a, vector b) {
return vector(this->x + b.x, this->y + b.y);
}
};
int main() {
vector a = vector(2, 3);
vector b = vector(4, 4);
vector c = vector.add(a, b);
printf("%f, %f", c.x, c.y);
return 0;
}
// expected output from this function: 6, 7
上面的代码是我想要的一个例子,所以发生的事情背后的推理是多余的,我知道有一个向量类,我确信有一个更简单的方法来做这个代码,但是这是我想要的根功能。
在这种语言中这甚至可能吗?
int main() {
vector a = vector(2, 3);
vector b = vector(4, 4);
this works: vector c = a.add(a, b);
this !works: vector c = vector.add(a, b);
printf("%f, %f", c.x, c.y);
return 0;
}
我知道这行得通,但我要做的就是摆脱在 a.add(); 中需要 A 引用; 我试过静态函数,研究 std::functional 的东西,操作重载,但我可能误解了一些东西并遇到了一个解决方案 提前致谢!
答案 0 :(得分:1)
您可以在类中定义静态函数。
#include <stdio.h>
#include <stdlib.h>
struct vector {
float x, y;
// only recently figured out you could do this
// instead of vector() {x = 0.0; y = 0.0} etc.
vector() : x(0.0), y(0.0) {}
vector(float _x, float _y) : x(_x), y(_y) {}
// add "static"
static vector add(vector a, vector b) {
return vector(a.x + b.x, a.y + b.y); // use correct object
}
};
int main() {
vector a = vector(2, 3);
vector b = vector(4, 4);
vector c = vector::add(a, b); // use :: instead of .
printf("%f, %f", c.x, c.y);
return 0;
}