gpt4 book ai didi

c++ - 如何理解这个声明中的typedef

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:52:36 27 4
gpt4 key购买 nike

最近看了Effective C++这本书,第35条里面有一个关于typedef的声明让我很困惑。

class GameCharacter; // Question1: Why use forward declaration?

int defaultHealthCalc(const GameCharacter& gc);

class GameCharacter{

public:
typedef int (*HealthCalcFunc)(const GameCharacter&); // Question 2: What does this mean?

explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc)
: healthFunc(hcf)
{}

int healthValue() const
{return healthFunc(*this); }

private:
HealthCalcFunc healthFunc;
};

所以我的第一个问题是:为什么作者在这里使用前向声明?有什么具体原因吗?

我的第二个问题是:如何理解 typedef 声明,以及如何使用它?我只知道 typedef int MyInt;

最佳答案

So my first question is that why the author use forward declaration here?

因为函数defaultHealthCalc的声明使用了const GameCharacter&作为参数的类型,所以需要提前声明GameCharacter

And my second question is how to understand the typedef declaration

它声明了一个类型名称HealthCalcFunc,这是一种指向函数的指针类型,它以const GameCharacter&为参数并返回int

and how to use it?

正如代码示例所示,

explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc) // declare a parameter with type HealthCalcFunc; 
// the default argument is function pointer to defaultHealthCalc
: healthFunc(hcf) // initialize healthFunc with hcf
{}

int healthValue() const
{return healthFunc(*this); } // invoke the function pointed by healthFunc

HealthCalcFunc healthFunc; // declare a member with type HealthCalcFunc

关于c++ - 如何理解这个声明中的typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42745514/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com