Re: Nonstatic member example?
On 31 d=E9c, 04:27, Salt_Peter <pj_h...@yahoo.com> wrote:
On Dec 30, 11:24 pm, fl <rxjw...@gmail.com> wrote:
Hi,
There is a question about nonstatic member. C++ primer says: A
nonstatic member is restricted to being declared as a pointer or
reference to an object of its class. It only gives an example of
pointer *b.
class Bar {
public:
private:
static Bar a; // OK
Bar *b; // OK
Bar c; // error
My question is how a nonstatic member is declared as a reference to an
object of its class. Because a reference is legal only after the
original variable has been declared, where is the original object? I
feel it is really bizarre. Could you give me an example? Thanks in
advance.
private variable
the original object, in a special case like this one, would have to
refer to itself, which would then basicly mean that such a class could
not have a static member since the static member has no 'this'.
Its a special case, don't dissmiss references. They solve many, many
problems.
[10.7] Should you use the this pointer in the constructor?http://www.paras=
hift.com/c++-faq-lite/ctors.html#faq-10.7
#include <iostream>
class A
{
const A& r_a;
public:
A() : r_a(*this) { }
A(const A& copy) : r_a(copy) { }
A& operator=(const A& rhv); // disabled
A const& get_r() const { return r_a; }
};
void foo(const A& r)
{
std::cout << "&r = " << &r;
std::cout << "\tr.r_a = " << &r.get_r();
std::cout << std::endl;
}
int main()
{
A a;
foo(a);
A another = a; // is NOT an assignment
foo(another);
}
/*
&r = 0x7fff0f2e1930 r.r_a = 0x7fff0f2e1930
&r = 0x7fff0f2e1920 r.r_a = 0x7fff0f2e1930
*/- Masquer le texte des messages pr=E9c=E9dents -
- Afficher le texte des messages pr=E9c=E9dents -
Hi,
I find the modified code,see below, has the same output as yours.
Why the overload:
A another = a; // is NOT an assignment
does not take effect? Thank you very much.
---------------------
#include <iostream>
class A
{
const A& r_a;
public:
A() : r_a(*this) { }
// A(const A& copy) : r_a(copy) { }
// A& operator=(const A& rhv); // disabled
A const& get_r() const { return r_a; }
};
void foo(const A& r)
{
std::cout << "&r = " << &r;
std::cout << "\tr.r_a = " << &r.get_r();
std::cout << std::endl;
}
int main()
{
A a;
foo(a);
A another; // = a; // is NOT an assignment
foo(another);
}