Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this separate definition cause an error?

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

like image 707
Johannes Schaub - litb Avatar asked Mar 01 '10 19:03

Johannes Schaub - litb


People also ask

What causes errors in experiments?

Common sources of error include instrumental, environmental, procedural, and human. All of these errors can be either random or systematic depending on how they affect the results. Instrumental error happens when the instruments being used are inaccurate, such as a balance that does not work (SF Fig.

What causes random error?

Some common sources of random error include: natural variations in real world or experimental contexts. imprecise or unreliable measurement instruments. individual differences between participants or units.

What are 3 sources of error in an experiment?

Physical and chemical laboratory experiments include three primary sources of error: systematic error, random error and human error.

What is a random error in an experiment?

Random errors in experimental measurements are caused by unknown and unpredictable changes in the experiment. These changes may occur in the measuring instruments or in the environmental conditions.


2 Answers

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

like image 71
Jacob McIntosh Avatar answered Oct 31 '22 13:10

Jacob McIntosh


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.

like image 22
Dan Avatar answered Oct 31 '22 14:10

Dan