c2512 error: no appropriate default constructor av

2019-07-04 12:25发布

问题:

I have encountered "c2512" error even if I declared the constructor. My code is like this: in my "first.h" file, I declared it like:

class myClass
{
public:
    tmpM ( cv::Mat& _model );
}

then in my "first.cpp" I did:

#include "first.h"
myClass::tmpM ( cv::Mat& _model )
{
    ...
}

Then I included this "first.h" in my "second.h", then included this "second.h" in my "third.h", and called this class in my "third.cpp" like this:

cv::Mat myMat ( height, width, CV_8UC3 );
tmpM aM ( myMat );

But this gives out an c2512 error, saying

no appropriate default constructor available

I indeed searched about this, and found I should build a default constructor by myself, and I tried to do it like this in my "first.h":

class myClass
{
public:
    tmpM ( cv::Mat& _model) {};
}

Then got an error saying:

function "myClass::tmpM" already has a body

I tried several other methods to do it but still couldn't solve it. I don't need to build a default constructor here I think, but still bothered with it. Could someone help me?

Edit

Ok, after your suggestions, I changed it into this form:

class myClass
{
public:
myClass(cv::Mat& _model ) : tmpM (_model)
{
}
private:
cv::Mat& tmpM;
};

Then in my "first.cpp", I got an error saying

declaration is incompatible

How could this be solved?

回答1:

The problem here appears to be that you've named your class something other than what you've named your constructor. They have to have the same name. Also, I'm presuming you wish the reference to the model you're passing in to be held by the object. If you want to preserve it as a reference it must be initialized in the the constructors initializer list.

You want:

class myClass
{
public:
    myClass(cv::Mat& _model ) : tmpM (_model)
    {
    }
private:
    cv::Mat& tmpM;
};


回答2:

It should be:

class myClass
{
public:
    myClass(cv::Mat& _model ) : tmpM (_model)
    {
    }
};

Your version declares a function (well, attempts to, because it's invalid syntax - missing return type) called tmpM, it doesn't initialize the member.

You have to do it as above because the member the member of that type doesn't have a default constructor, so you must initialize it in the initialization list of the constructor.



回答3:

default constructor is

class myClass {
public:
  myClass();
}