Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
761 views
in Technique[技术] by (71.8m points)

c++ - No default constructor found

I don't want to use the default constructor so I implement mine

class A
{
  public:
     A(int&i);
     A& operator=(const A& a);
     A(const A&a);
};

But in class B

class B
{
   A a;
   public:
     B(const A&a){this->a=a;}
}

Then the error:

no appropriate default constructor of A found.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a constructor initialization list, so the member a is initialized via the copy constructor:

B(const A&a):a(a){}

If you don't use a constructor initialization list, then the compiler first tries to initialize A a;, and only after assigns the other a to it. However, the first initialization fails because there is no default constructor provided. In general, it is recommended to always using the constructor initialization list when initializing members. In this way, instead of calling one constructor + one assignment operator, you only call the copy constructor.

I suggest changing the name of the member from a to e.g. _a, so the code becomes a bit more clear.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...