问题描述
在State.h中,我有
In State.h I have
em> StateFwd.hpp ,然后将您的 State.cpp 重命名为 State.hpp 。You could make a separate header just for forwarding, maybe called StateFwd.hpp and then rename your State.cpp to State.hpp.
我已经在示例中更新了我的答案,我们在评论中进行了讨论。
I've updated my answer with an example, following the discussion we had in the comments.
任何选择包含此标题的人都知道什么样的水果存在。
Anyone who chooses to include this header will know what kind of fruits exist.
#ifndef FRUIT_HPP #define FRUIT_HPP enum class Fruit { APPLE, ORANGE, BANANA }; #endif
village.hpp
村里有很多人因为他们的欲望而渴求水果。
village.hpp
The village is full of people driven by their lust for fruit.
#ifndef VILLAGE_HPP #define VILLAGE_HPP enum class Fruit; namespace farmer { bool is_fruit_for_sale(Fruit fruit); float get_cost_of_fruit(Fruit fruit); } namespace blind_but_greedy_merchant { bool sell_fruit(Fruit fruit, float money); } namespace peasant { inline bool buy_fruit(Fruit fruit, float money) { return blind_but_greedy_merchant::sell_fruit(fruit, money); } } #endif
农民.cpp
这个农夫只生长苹果和橘子,所以他从来没有香蕉出售。
farmer.cpp
This farmer only grows apples and oranges, so he never has bananas for sale
#include "fruit.hpp" namespace farmer { bool is_fruit_for_sale(Fruit fruit) { switch ( fruit ) { case Fruit::APPLE: case Fruit::ORANGE: return true; case Fruit::BANANA: return false; } return false; } float get_cost_of_fruit(Fruit fruit) { switch ( fruit ) { case Fruit::APPLE: return 1.00f; case Fruit::ORANGE: return 2.50f; case Fruit::BANANA: return 200.0f; } return 0.0f; } }
merchant.cpp
这个商人从贪婪中失明。他不能再看到他卖的是什么样的
水果。他仍然知道如何处理农夫,
传递客户的要求给农夫,同时为所有水果添加一个陡峭的利润
保证金。
这就是为什么不包括fruit.hpp 。#include "village.hpp" namespace blind_but_greedy_merchant { bool sell_fruit(Fruit fruit, float money) { if ( !farmer::is_fruit_for_sale(fruit) ) { return false; } float inflatedcost = farmer::get_cost_of_fruit(fruit) * 3; if ( money < inflatedcost ) { return false; } return true; } }
example.cpp
这一切都在一起。在我们的例子中,我们想让农民去买一些水果。
我们知道我们想要什么样的水果;一根香蕉。因此,我们需要包括 fruit.hpp ,否则我们不能告诉农民去为我们买一个BANANA。example.cpp
This pulls it all together. In our example, we want the peasant to go buy some fruit.We know exactly what kind of fruit we want; a BANANA. Therefore we need to include fruit.hpp, otherwise we could not tell the peasant to go and buy a BANANA for us.
在这种情况下,知道什么样的水果存在的人是我们( example.cpp )和农夫( farmer.cpp )。
农民甚至不需要知道。这就像我们给了他一张折叠的纸,说我们想要什么水果,但我们告诉他不要看它。The only two people in this scenario who know what kind of fruit exist are us (example.cpp) and the farmer (farmer.cpp).The peasant doesn't even need to know. It's like we've given him a folded piece of paper that says what fruit we want, but we've told him not to look at it. And he just hands it to the merchant, who can't read, so he just passes it on to the farmer.
#include "village.hpp" #include "fruit.hpp" int main() { peasant::buy_fruit(Fruit::BANANA, 25.0f); return 0; }这篇关于Forward声明枚举类不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!