c++ - Symbol vector could not be resolved -
#include <iostream> #include <vector> using namespace std; class block{ public: long nx,ny; vector<long> s; block(long &x, long &y):nx(x),ny(y),vector<long> s((x+1)*(y+1),0) {} }; int main() { block b(2,2); for(int i=1;i<=9;i++) { cout<<b.s(i); } cout << "!!!hello world!!!" << endl; // prints !!!hello world!!! return 0; }
compiled , error message shows symbol "vector" not resolved. mistake? want define class contain variable dimension vector initialize.
#include <iostream> #include <vector> using namespace std; class block{ public: long nx,ny; vector<long> s; block(long &x, long &y):nx(x),ny(y),s((x+1)*(y+1),0) {} }; int main() { block b(2,2); for(int i=0;i<=9;i++) { cout<<b.s[i]; } cout << "!!!hello world!!!" << endl; // prints !!!hello world!!! return 0; }
still got problem @ block b(2,2); error message:no instance of constructor "block::block" matches argument list
why? thanks!
firstly:
vector<long> s((x+1)*(y+1),0)
should be:
s((x+1)*(y+1),0)
should not repeat type s
. meanwhile constructor should be:
block(const long &x, const long &y): nx(x), ny(y), s((x + 1) * (y + 1), 0) { }
if need reference. since otherwise, when
block b(2,2);
inside main
, give error because constructor takes long&
, passing int constants. deep reason related lvalue , rvalues: integer constants rvalues, however, long&
reference non-const long, lvalue reference. according blog: lvalues, rvalues , references
an lvalue reference (to non-const type) reference can initialized lvalue. well, lvalues not render const or volatile types. rvalue reference (to non-const type) reference can initialized rvalue (again, rvalues not designate const or volatile types). lvalue reference const type reference can initialized rvalues , lvalues alike (rendering constant , non-constant types).
further, according c++11 standard: section 4.1 standard conversions:
standard conversions implicit conversions defined built-in types. standard conversion sequence sequence of standard conversions in following order:
— 0 or 1 conversion following set: lvalue-to-rvalue conversion, array-to-pointer conversion, , function-to-pointer conversion.
— 0 or 1 conversion following set: integral promotions, floating point promotion, integral conversions, floating point conversions, floating-integral conversions, pointer conversions, pointer member conversions, , boolean conversions.
— 0 or 1 qualification conversion.
there no rvalue-to-lvalue conversion. why saw compile error. adding const
before long&
make able initialized rvalues, that's why error goes away after change.
secondly,
cout<<b.s(i);
should be:
cout<<b.s[i];
you should use []
access vector elements.
thirdly, vector index starts 0
,
for(int i=1;i<=9;i++)
should be
for(int i=0;i<9;i++)
otherwise, index out of bounds. see working example here: http://ideone.com/ylt3mg
Comments
Post a Comment