简体   繁体   中英

error: no matching function call when adding parameters to class constructor

I have a class, "a", that has an instance of class "b". The following code gives the error in the title of the question, but when I change b to not take any arguments, the code runs without errors.

class b
{
public:
    b(int);
};

class a
{
  public:
  b bObj;
      a(int arg1, const std::string& arg2);
};

a::a(int arg1, const std::string& arg2){
  bObj = b(5);
}

b::b(int IDD2){
  srand(time(0)+IDD2);
}

Running this code where "b" has no arguments works, but I actually need to pass in a value. Why is it giving this error?

In the constructor of a , bObj must be constructed before you enter the function body. But there is no zero argument constructor for b , and you have not provided a default initializer, so you get an error.

Instead, you can initialize bObj before reaching the body of the constructor by using a member initializer list:

a::a(int arg1, const std::string& arg2) : bObj(5) {}

Or provide the default inside the class:

class a
{
  public:
  b bObj = 5;
  a(int arg1, const std::string& arg2);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM