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
444 views
in Technique[技术] by (71.8m points)

c++ - error: no matching function for call to

Heres my error...

"In constructor 'NumGame::NumGame(int&)': error: no matching function for call to 'Category::Category()'"

Ive looked at a few similar questions here but cant seem to find an answer. I have a base class Category and NumGame is inherited from it but wont compile.

class Category {

public:
    void virtual selection(int&);
    Category(int&);
    virtual ~Category(){};
private:
    int myRandNum;
};

Category::Category(int& a){
    myRandNum = a;
}

void Category::selection(int& a){
    cout << "I am NumGame version number... " << a << endl;
    cout << "Now Im playing... " << myRandNum << endl;
}

class NumGame : public Category {

public:
    void selection(int&);
    NumGame(int&);
    ~NumGame(){};
private:
    int myRandNum;
};

NumGame::NumGame(int& b){
    myRandNum = b;
}

void NumGame::selection(int& b) {

}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Reason for the error:

When you create an instance of derived class NumGame the Base class Category no argument constructor is called to create the Categorypart of the object. Your class doesn't have one and the compiler complains about it.

Why the compiler did not synthesize the default constructor?

Once you provide any constructor for your class the compiler does not synthesize the constructor which does not take any argument for you, You have to provide that yourself if your code uses one.

Solutions:

There are two ways to avoid the error:

Call the appropriate available constructor in Base class Catoegory subobject through Member Initializer list. This removes the scenario where your code uses a no argument constructor.

NumGame::NumGame(int& b) : Category(b)
{

}

OR

You need to provide a no argument constrcutor for Category class yourself:

Category::Category()
{

}

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

...