C ++ Constructors

I wrote this code:

class A {
  public:
    A(){d=2.2;cout<<d;}
    A(double d):d(d){cout<<d;}
    double getD(){return d;}

  private:
    double d;
};

class Bing  {
  public:
    Bing(){a=A(5.3);}
    void f(){cout<<a.getD();}
  private:
    A a;
};

int main() {
  Bing b;
  b.f();
}

i get the result: 2.2 5.3 5.3 instead of 5.3 5.3. is it something in the constructor .... why am i getting this? how can i fix this?

+3
source share
8 answers

There Aare two constructors in your class : the default constructor, which sets dto 2.2, and the constructor takes a double, which sets dto what you pass to the constructor.

- A Bing. - Bing. Bing , . , :

Bing() : a(5.3) { }
+10

, .

Bing :

Bing() : a(5.3)
{
}

A ( " " ), A ( ).

+5

a , .

+2

:

    Bing(){a=A(5.3);}

To:

    Bing():a(5.3){}

.

, . .

+1

, ++. , , .:)

, . ++ . , .

, (-) , c-tor, .

+1

A a Bing. a Bing, a . p >

Bing a. Bing :

Bing(): a(5.3) {}
+1

2.2, A Bing 's:

Bing(){a=A(5.3);}
0

As already mentioned, you must initialize the elements Aand Bingin the relevant contructor initialization lists. You can also set A::dto the default, so you do not need two constructors in A. That is, you have:

class A { 
  public: 
    A(){d=2.2;cout<<d;} 
    A(double d):d(d){cout<<d;} 
    double getD(){return d;} 

  private: 
    double d; 
};

You can rewrite it as:

class A { 
  public: 
    A(double d=2.2) : d(d) { cout << d; } 
    double getD() { return d; } 

  private: 
    double d; 
};
0
source

Source: https://habr.com/ru/post/1750502/


All Articles