Request a member X of Y that is not of class Z

When trying to compile the following C ++ code snippet (full source code below)

A::A(istream& i) { vector<string> words( istream_iterator<int>(i), istream_iterator<int> ); words.begin(); } 

I get an error

 istream_it.cpp:12: error: request for member 'begin' in 'words', which is of non-class type 'std::vector<int, std::allocator<int> >( std::istream_iterator<int, char, std::char_traits<char>, long int>, std::istream_iterator<int, char, std::char_traits<char>, long int>)' 

I know that this error is usually caused by a random declaration of a function using the no-parameters operator, as in

 string s(); s.size(); 

but in this case, I already deleted all the unnecessary code and still can not understand what exactly is happening, or what will be the correct syntax.

Full source:

 #include <sstream> #include <vector> #include <iterator> #include <string> using namespace std; class A { public: A(istream& i) { vector<int> words(istream_iterator<int>(i), istream_iterator<int> ); words.begin(); } }; int main(int argc, char** argv) { istringstream iss("1 2 3"); A a(iss); return 0; } 
+4
source share
1 answer

Right,

 vector<int> words(istream_iterator<int>(i), istream_iterator<int> ); 

it is a function with a name that contains two istream_iterator<int> parameters, one of which has the name i and the other does not have a name and returns a vector. Change to this:

 vector<int> words((istream_iterator<int>(i)), istream_iterator<int>() ); 

The first brackets added (istream_iterator<int>(i)) make this an expression, so there will be no ambiguity. Other parentheses of istream_iterator<int>() are required as you construct temporary ones. The type itself, for example, istream_iterator<int> , does not create a temporary one.

+7
source

Source: https://habr.com/ru/post/1334949/


All Articles