[C++] Cum scriu o clasa cu membri tip referinta?

Despre limbajul de programare C++ si biblioteca standard STL (forum moderat)
Post Reply
User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3776
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi
Contact:

[C++] Cum scriu o clasa cu membri tip referinta?

Post by Ovidiu Cucu » 24 May 2011, 13:33

Intrebare
Cum trebuie implementata o clasa care are membri tip referinta?

Raspuns
  1. Trebuie sa aiba cel putin un constructor definit de utilizator.

    Code: Select all

    class CFoo
    {
       int& r;
    }; // Warning: default constructor could not be generated
       // Warning: class 'CFoo' can never be instantiated -  
       //          user defined constructor required
    
    int main()
    {
       CFoo foo; // Error: no appropriate default constructor available
       return 0;
    }
  2. Membrii tip referinta trebuie initializati in lista de initializare a constructorilor.

    Code: Select all

    class CFoo
    {
       int& r;
    public:
       CFoo(int i) {r = i;} // Error: 'CFoo::r' : must be initialized in 
                            // constructor base/member initializer list
    };
  3. Trebuie definit operatorul de atribuire.

    Code: Select all

    class CFoo
    {
       int& r;
    public:
       CFoo(int i) : r(i) {} 
    }; // Warning: assignment operator could not be generated
    
    int main()
    {
       CFoo foo1(777), foo2(888);
       foo2 = foo1; // Error: 'operator =' function is unavailable in 'CFoo'
       return 0;
    }
La cele enumerate mai sus, se adauga si observatiile ca parametrul care seteaza referinta trebuie trimis tot prin referinta si ca, in general, odata ce e definit operatorul de atribuire e bine sa fie definit si constructorul de copiere (valabila si vice versa).

O implementare minimala a clasei care are un membru tip referinta este ca mai jos.

Code: Select all

class CFoo
{
   int& m_r;
public:
   CFoo(int& r) : m_r(r) {}
   CFoo(const CFoo& rFoo) : m_r(rFoo.m_r) {}
   CFoo& operator=(const CFoo& rFoo)
   {
      if(this != &rFoo)
      {
         m_r = rFoo.m_r;
      }
      return *this;
   }
};

Code: Select all

int main()
{
   int i = 777, j = 888;
   CFoo foo1(i);
   CFoo foo2(j);
   foo1 = foo2;

   // Hurray, all above is okay!
   return 0;
}
Resurse
  • ISO/IEC 14882:2003 Programming languages — C++



Post Reply