Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...