如何创建具有多个标识符的函数

How do I create a function with multiple identifiers?

本文关键字:标识符 函数 何创建 创建      更新时间:2023-10-16

我想创建一个函数,在不同的上下文中,最好用不同的名字来称呼它。

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所说的:同一个函数不要有两个名字。这是令人困惑的。