Konstruktory: jaką funkcję spełnia poniższy zapis?

0

Witam, bawię się ostatnio c++ obiektowym i nie mogę rozgryźć jaką funkcję ma zapis " : a( bok ) {}":

 class Kwadrat : public Figura 
 {
   public:
     Kwadrat( const float bok ) : a( bok ) {}
 
     float pole() const 
     {
       return a * a;
     }
   private:
     float a; // bok kwadratu
 }; 
1

Constructor initialization list. Możesz ustawiać wartości pól klasy w ten sposób.

0

@radek448 jeśli polem twojej klasy jest obiekt innej klasy to jak wywołasz konstruktor? ;)

0

Kwadrat( const float bok ) : a( bok ) {}

mniej-więcej tyle co

Kwadrat( const float bok )
{
    a = bok;
}
0

przeanalizuj ten kod:

#include <cstdio>
struct A
{
    A() { puts("konstruktor domyslny"); }
    A(int) { puts("konstruktor z parametrem"); }
    A(const A& a) { puts("konstruktor kopiujacy"); }
    void operator=(const A& a) { puts("operator przypisania"); }
};

struct B
{
    B() { a = A(2); }
    B(const A& arg, int) : a(arg) {}
    B(int) {  }
    B(double) : a(0) {  }
    A a;
};

int main()
{
    B b1;
    puts("---");
    B b2(b1.a, 0);
    puts("---");
    B b3(0);
    puts("---");
    B b4(0.0);
    return 0;
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1