为什么这个单独的定义会导致错误?
挑战:
我的代码无法编译。你能找出问题所在吗?有一次让我很头疼。
// header
namespace values {
extern std::string address;
extern int port;
}
// .cpp file
std::string ::values::address = "192.0.0.1";
int ::values::port = 12;
第一眼看上去是正确的。有多少错误,哪些是错误!?
Challenge:
I have this code that fails to compile. Can you figure out what's wrong? It caused headache to me once.
// header
namespace values {
extern std::string address;
extern int port;
}
// .cpp file
std::string ::values::address = "192.0.0.1";
int ::values::port = 12;
It looks correct on the first sight. How many and which are the errors!?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个错误:
是正确的形式,否则解析是
并且在“字符串”内不存在带有成员“地址”的成员“值”...
它将适用于内置类型,因为它们永远不能包含成员..所以 int ::values 是一个明确的解析,int ::values,因为先验没有意义。
也有效。请注意,如果您输入 def int sometype;使用某种类型会遇到与上面的字符串相同的问题,但使用“int”则不会。
One error:
is the proper form, otherwise the parse is
and there is no member "values" with a member "address" inside "string"...
it will work for builtin types, as they cannot ever contain members.. so int::values is an unambigous parse, int ::values, because the prior doesn't make sense.
works too. Note that if you typedef int sometype; that you'd have the same problem using sometype as you do with string above, but not with "int".
我迟到了,但我更愿意将 .cpp 文件编写为:
当然,这并不能解决您在
friend
声明中遇到的问题。I'm late to the game, but I would have preferred to write the .cpp file as:
Of course that doesn't solve the problem you had with the
friend
declaration.