Re: Stroustrup 5.5 References
Hi
arnuld wrote:
this i the example programme. it has many errors, i am not able to
make anything out it:
Well, it's all in the error messages...
#include<iostream>
#include<string>
#include<vector>
struct Pair;
double& get_value(const std::string&);
std::vector<Pair> pairs_list;
int main()
{
std::string get_name;
while(std::cin >> get_name)
get_value(get_name)++;
for(std::vector<Pair>::const_iterator p=pairs_list.begin(); p !=
pairs_list.end(); ++p)
{
std::cout << p->name
Here, you try to access a Pair, but the definition of Pair is still
unknown, thus:
5.5_references.cpp:39: error: invalid use of undefined type 'const
struct Pair'
5.5_references.cpp:24: error: forward declaration of 'const struct Pair'
<< " : "
<< p->value
The same again:
5.5_references.cpp:41: error: invalid use of undefined type 'const
struct Pair'
5.5_references.cpp:24: error: forward declaration of 'const struct Pair'
<< std::endl;
}
return 0;
}
5.5_references.cpp: At global scope:
struct Pair
{
std::string name;
double val;
}
double& get_value(const std::string& s)
5.5_references.cpp:54: error: new types may not be defined in a return type
5.5_references.cpp:54: note: (perhaps a semicolon is missing after the
definition of 'Pair')
Indeed, your definition of Pair is missing a semicolon. (Notice that you
could e.g. define a Pair-object p by "struct Pair { [...] } p;". The
same is _not_ allowed for functions, but to the compiler, it looks like
that is what you want to do: struct Pair { [...] } [...] get_value(const
std::string& s) { [...] })
And furthermore, it looks like you give two return types, Pair and
double&, so...
5.5_references.cpp:54: error: two or more data types in declaration of
'get_value'
Of course, this differs from the previous declaration only in the return
type and you cannot overload functions on return types:
5.5_references.cpp:54: error: new declaration 'Pair& get_value(const
std::string&)'
5.5_references.cpp:25: error: ambiguates old declaration 'double&
get_value(const std::string&)'
{
/* maintains aset of Pairs, if "s" is found
returns its corresponding value */
const int my_val = 0;
for(int i=0; i < pair_list.size(); i++)
^^^^^^^^^
Wait, it was pair!s!_list before! What is pair_list?
5.5_references.cpp:61: error: 'pair_list' was not declared in this scope
if(s == pairs_list[i].name)
return pairs_list[i].val;
Pair p = { s, my_val };
pairs_list.push_back(p); // adds pair at the end
return pairs_list[pairs_list.size() - 1].val; // actually return 0
(zero)
}
Finally, there are some errors due to previous errors:
5.5_references.cpp:63: error: invalid initialization of reference of
type 'Pair&' from expression of type 'double'
5.5_references.cpp:68: error: invalid initialization of reference of
type 'Pair&' from expression of type 'double'
Remember: the compiler is confused about the return type of get_value!
hth
Markus