c++ - 没有结构引用的 c++ 函数调用
问题描述
我是 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 事物,操作重载,但我可能误解了某些东西并遇到了解决方案提前谢谢!
解决方案
您可以在类中定义静态函数。
#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;
}
推荐阅读
- python - 在分析 csv 文件中的数据(平均值、中位数、众数等)时需要帮助
- powershell - 如果 & 号命令失败,如何自动停止 powershell。示例: & $cmd # 现在它失败了
- sql - 连接失败 - 定义必须采用 SELECT 语句的形式
- r - 分隔逗号分隔值不同行
- c++ - C++17:如何控制执行策略中的线程数?
- javascript - 转换为 django 模板时出现 Javascript 问题
- json - 如何在逻辑应用程序中搜索 Azure 表存储 JSON 响应?
- sql - 带有日期列的动态数据透视表
- html - 如何在背景图像上获取社交媒体图标?
- javascript - 如何将类添加/切换到元素以便将汉堡菜单切换到 X 以便关闭并再次返回