Why does this separate definition cause an error?

烈酒焚心 提交于 2019-12-23 07:56:10

问题


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!?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/2358524/why-does-this-separate-definition-cause-an-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!