How to separate constructor declared explicitly into .h & .cpp files?

Refresh

December 2018

Views

103 time

1

Here is a piece of code which I found in OpenCV tutorial (source https://github.com/Itseez/opencv/blob/master/samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp). Because the code is all in one file I try to separate it into header and cpp. My problem is I cannot find out how to do it correctly not to generate error C4430: missing type specifier - int assumed. Note: C++ does not support default-int.

class MyData
{
public:
MyData() : A(0), X(0), id() {}
explicit MyData(int) : A(97), X(CV_PI), id("mydata1234") // explicit to avoid implicit conversion
{}
void write(FileStorage& fs) const //Write serialization for this class
{
fs << "{" << "A" << A << "X" << X << "id" << id << "}";
}

public: // Data Members
int A;
double X;
string id;
};

So this is the part which I am stuck at:

MyData() : A(0), X(0), id() {}
explicit MyData(int) : A(97), X(CV_PI), id("mydata1234") // explicit to 

A declaration (header file) which I tried:

class MyData
{
    public: // Data Members
        int A;
        double X;
        std::string id;

        MyData() ;
        explicit MyData(int);

    void write(cv::FileStorage& fs) const;
    void read(const cv::FileNode& node);
};

#endif

The thing in .cpp

MyData::MyData() : A(0), X(0), id() {}  // this is simple

But what next?

MyData::MyData(int) : 
    A(97), X(CV_PI), id("mydata1234") {};
MyData::write(cv::FileStorage& fs) const 
{ // ... it will stuck here C4430 
 }

using Visual Studio 2010

3 answers

1

In your hpp when you are declaring it should be something like this :

class Name{
 .....some other functions  ....
void write(cv::FileStorage& fs);
};

and in your cpp you need first to include your hpp and then :

void Name::write(cv::FileStorage& fs)
{
    .......body...
}

So first say the type of the funciton (in this case void) then name of the class then :: and then the function name .

hope this helped :)

1
MyData::write(cv::FileStorage& fs) const 
{ // ... it will stuck here C4430 
 }

C4430 is "missing type specifier". It's because the MyData::write() implementation contains no return type. Only constructors should omit a return type. Change it to void MyData::write(cv::FileStorage& fs) const to match its declaration.

1

To add a body for your write method outside of the class definition the format is :

return-type classname::methodname(parameters)
{
}

So in this case:

void MyData::write(cv::FileStorage& fs) const 
{ 

}