如何创建具有多个标识符的函数
How do I create a function with multiple identifiers?
我想创建一个函数,在不同的上下文中,最好用不同的名字来称呼它。
class box(){
private:
float posX;
float size = 10;
public:
float speedX;
float left(){ return posX; } //Any way to combine these?
float posX(){ return posX; } //Any way to combine these?
float right(){ return posX + size; }
};
box a;
box b;
bool checkCollide(){
if(a.right() < b.left()){ return 0; } //Not colliding
if(b.right() < a.left()){ return 0; } //Not colliding
return 1; //Colliding
} //Comparing right and left makes more sense than anything else
void physics(){
a.posX() += a.speedX;
b.posX() += b.speedX;
//Adding speed to position makes more sense than
//adding speed to "left"
}
//Loop physics X times per second, and do something if there's a collision
或者,有没有更好的方法?我可以让左/右成员自动更新任何时候的位置或大小的变化,而不是重新计算每次调用?
如果您真的有义务这样做,那么只需让一个函数调用另一个函数:
// the function that does the hard job
float foo(float a, float b)
{
// some heavy and complicated code
// ...
// some more black magic, etc.
// finally:
return sqrt(a * a + b * b);
}
// the function that pretends to do the hard job
float bar(float a, float b)
{
return foo(a, b);
}
但是你最好不要这样做,这是很糟糕的风格。不同的名称=>不同的任务。相同任务=>相同名称。不要伤害你同伴的直觉。: -)
Yes - Not写两个函数,在开始做同样的事情。我只是希望它们不要发散。那你就有麻烦了!
如果您使用的是c++ 11,或者使用Boost时,您可以将left()
函数绑定到std::function
变量。与c++ 11:
class box {
// ...
public:
// ...
float left() { return posX; }
const std::function<float()> posx = std::bind(&box::left, this);
需要const
,否则posx
可能会在运行时改变指向不同的函数。
如果你不使用c++ 11编译器,而是使用Boost,那么它不是那么富有表现力,因为你必须在函数中初始化posx
:
class box {
// ...
public:
box() : posx = boost::bind(&box::left, this);
// ...
float left() { return posX; }
const boost::function<float()> posx;
在这两种情况下,你都可以这样做:
box b;
b.left();
b.posx();
与使用posx()
函数并在其中调用left()
相比,我认为这个方法没有任何优势。但这是可能的,因此值得提及。
但我同意H2CO3所说的:同一个函数不要有两个名字。这是令人困惑的。
相关文章:
- 在模板化函数中重新定义(忽略)的 SWIG 标识符
- 在 c++ 中找不到此函数的标识符
- 声明与 const 变量和成员函数相同的标识符
- 我的函数调用 (C++) 中的未声明标识符
- 函数声明中的 WINAPI 标识符C++ DLL 入口点函数中的标识符
- 由于值返回函数中的错误,程序无法编译.它说未声明的标识符
- im调用函数时找不到标识符?
- 将函数标识符作为右值引用传递并对其应用 std::move()
- 错误 C2146:语法错误:按函数传递映射时标识符 mType 之前缺少','
- C 如何从构造函数中声明(错误C2065未宣布的标识符)
- C++ 多态构造函数错误;标识符未定义
- 调用函数时未定义标识符"function_name"
- 为什么在函数参数编译中没有标识符的const关键字
- 当通过函数中的参考调用时,标识符不确定
- 在检查传递函数标识符时是否获得模板参数时遇到问题
- 函数参数中未声明和未定义的标识符
- 使用函数模板中静态局部变量的地址作为类型标识符是否安全
- C++构造函数:数字常量之前的预期标识符
- 找不到QT 5.6 update()函数标识符
- 不存在的标识符在非启用函数模板中用作默认参数