tw********@gmail.com wrote:
Can anyone explain why this file won't compile? The errors I'm getting
in VS.Net 2003 are below.
============================
c:\sri\sw\scs\SCS\src\TaskPlans\main.cpp(24): error C3861: 'str':
identifier not found, even with argument-dependent lookup
c:\sri\sw\scs\SCS\src\TaskPlans\main.cpp(23): error C2040: 'str' :
'int' differs in levels of indirection from 'std::string &'
c:\sri\sw\scs\SCS\src\TaskPlans\main.cpp(23): error C2143: syntax error
: missing ';' before '.'
c:\sri\sw\scs\SCS\src\TaskPlans\main.cpp(23): error C2501: 'str' :
missing storage-class or type specifiers
============================
std::string& string_instance()
{
static std::string msg("Hello");
return msg;
}
std::string & str = string_instance();
str.c_str(); //--------->comment this line and the file will compile
const char * ptr = str.c_str();
void foo()
{
std::string & str = string_instance();
str.c_str();
const char * ptr = str.c_str();
}
int main(int, char *)
{
return 0;
}
When I compiled your example, verbatim, with g++ (GCC) 3.3.1 (cygming
special), I get the following errors:
$ g++ -o junk.exe junk.cpp
junk.cpp:1: error: syntax error before `&' token
junk.cpp:7: error: syntax error before `&' token
junk.cpp:8: error: syntax error before `.' token
junk.cpp:9: error: `str' was not declared in this scope
junk.cpp: In function `void foo()':
junk.cpp:13: error: `string' undeclared in namespace `std'
junk.cpp:13: error: `str' undeclared (first use this function)
junk.cpp:13: error: (Each undeclared identifier is reported only once
for each
function it appears in.)
junk.cpp:13: error: `string_instance' undeclared (first use this function)
I added "#include <string>" and get the following error:
junk.cpp:10: error: syntax error before `.' token
Line 10 is the line with "str.c_str();" on it.
My understanding (and I will get corrected if I wrong), is that
the line "str.c_str();" is a statement and must be enclosed
within a function. In other words, this would be the equivalent
of:
#include <iostream>
std::cout << "This is not valid." << endl;
int main(void)
{
return 0;
}
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library