为什么这个单独的定义导致错误? [英] Why does this separate definition cause an error?

查看:110
本文介绍了为什么这个单独的定义导致错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

挑战:

我的代码无法编译。你能弄清楚出了什么问题吗?它使我头痛一次。

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;

它看起来正确。

推荐答案

一个错误:

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

是正确的格式,否则解析为

is the proper form, otherwise the parse is

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

并且没有成员values

and there is no member "values" with a member "address" inside "string"...

它将适用于内置类型,因为它们不能包含成员..所以int :: values是一个无歧义的解析,int :: values,因为前面的'有意义。

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

注意,如果你typedef int sometype;你会有同样的问题使用sometype作为字符串上面,但不是与int。

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

这篇关于为什么这个单独的定义导致错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆