Firstly:
vector<long> s((x+1)*(y+1),0)
should be:
s((x+1)*(y+1),0)
should not repeat the type for s
.
Meanwhile the constructor should be:
block(const long &x, const long &y):
nx(x), ny(y), s((x + 1) * (y + 1), 0)
{
}
if you really need reference. Since otherwise, when you do
block B(2,2);
inside main
, it will give you error because constructor takes long&
, you are passing int constants. Deep reason about this is related to lvalue and rvalues: integer constants are rvalues, however, long&
is reference to non-const long, which is lvalue reference. According to this blog: lvalues, rvalues and references
An lvalue reference (to non-const type) is a reference that can be initialized with an lvalue. Well, only with those lvalues that do not render const or volatile types. An rvalue reference (to non-const type) is a reference that can be initialized with an rvalue (again, only with those rvalues that do not designate const or volatile types). An lvalue reference to const type is a reference that can be initialized with rvalues and lvalues alike (rendering constant and non-constant types).
Further, according to C++11 standard: Section 4.1 standard conversions:
Standard conversions are implicit conversions defined for built-in types. A standard conversion sequence is a sequence of standard conversions in the following
order:
— Zero or one conversion from the following set: lvalue-to-rvalue conversion, array-to-pointer conversion,
and function-to-pointer conversion.
— Zero or one conversion from the following set: integral promotions, floating point promotion, integral
conversions, floating point conversions, floating-integral conversions, pointer conversions, pointer to
member conversions, and boolean conversions.
— Zero or one qualification conversion.
There is no rvalue-to-lvalue conversion. This is why you saw that compile error. Adding const
before long&
make it be able to be initialized with rvalues, that's why the error goes away after the change.
Secondly,
cout<<B.s(i);
should be:
cout<<B.s[i];
You should use []
to access vector elements.
Thirdly, vector index starts from 0
, so
for(int i=1;i<=9;i++)
should be
for(int i=0;i<9;i++)
Otherwise, index out of bounds. See a working example here: http://ideone.com/YLT3mG