为什么这个单独的定义会导致错误?

发布于 2024-08-23 13:27:30 字数 300 浏览 8 评论 0原文

挑战:

我的代码无法编译。你能找出问题所在吗?有一次让我很头疼。

// 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一抹微笑 2024-08-30 13:27:30

一个错误:

std::string values::address = "192.0.0.1"; 

是正确的形式,否则解析是

std::string::values::address = "192.0.0.1"; 

并且在“字符串”内不存在带有成员“地址”的成员“值”...

它将适用于内置类型,因为它们永远不能包含成员..所以 int ::values 是一个明确的解析,int ::values,因为先验没有意义。

std::string (::values::address) = "192.0.0.1"; 

也有效。请注意,如果您输入 def int sometype;使用某种类型会遇到与上面的字符串相同的问题,但使用“int”则不会。

One error:

std::string values::address = "192.0.0.1"; 

is the proper form, otherwise the parse is

std::string::values::address = "192.0.0.1"; 

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.

std::string (::values::address) = "192.0.0.1"; 

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".

一城柳絮吹成雪 2024-08-30 13:27:30

我迟到了,但我更愿意将 .cpp 文件编写为:

// .cpp file
namespace values {
  std::string  address = "192.0.0.1";
  int          port    = 12;
}

当然,这并不能解决您在 friend 声明中遇到的问题。

I'm late to the game, but I would have preferred to write the .cpp file as:

// .cpp file
namespace values {
  std::string  address = "192.0.0.1";
  int          port    = 12;
}

Of course that doesn't solve the problem you had with the friend declaration.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文