Re: basic question about references
From: Jonathan Mcdougall (jonathanmcdougall_at_DELyahoo.ca)
Date: 01/09/05
- Next message: Thomas Matthews: "Re: Pausing another process"
- Previous message: Johannes: "Pausing another process"
- In reply to: zapro: "basic question about references"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 08 Jan 2005 22:41:09 -0500
zapro wrote:
> Hello, I am learning C++ and having problems understanding references.
> Considering this piece of code:
>
> class NumSequence1 {
> protected:
> NumSequence1(std::vector<int> &re)
> : _relems(re) {}
> std::vector<int> &_relems;
> };
>
> class Fibonacci1 : public NumSequence1 {
> public:
>
> Fibonacci1()
> : NumSequence1(&_elems) {} // ERROR
Change this to
Fibonacci1()
: NumSequence1(_elems)
{
}
> // ....
>
> protected:
> static std::vector<int> _elems;
> };
>
>
> this code doesn't compile and reports the errors:
>
> error: no matching function for call to
> `NumSequence1::NumSequence1(std::vector<int, std::allocator<int> >*)'
std::vector<int, std::allocator<int> >* is a
pointer. Just remove the allocator part to make
it clearer
std::vector<int>*
> error: candidates are: NumSequence1::NumSequence1(const NumSequence1&)
That's the copy-ctor.
> error: NumSequence1::NumSequence1(std::vector<int, std::allocator<int> >&)
That's your constructor. It expects a reference,
not a pointer. Look at this example.
void f(int *p); // a pointer
void f(int &r); // a reference
int main()
{
int i = 10;
f(&i); // calls f(int*)
f(i); // calls f(int&)
}
Passing by reference does not require any
operators from the user's side. It was mainly
introduced for operator overloading because using
pointers would have been impossible. It gives a
clean syntax for the user and makes it easier for
the function to use the object.
void f(int *p)
{
*p = 10; // clumsy
}
void f(int &r)
{
r = 10; // clean
}
Jonathan
- Next message: Thomas Matthews: "Re: Pausing another process"
- Previous message: Johannes: "Pausing another process"
- In reply to: zapro: "basic question about references"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|