Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to declare type conversion in header file and implement in cpp file?

it doesn't work for me.
i have a header file and a cpp file.
need to define a conversion operator from my class to INT, but it gives me "syntax error" when declaring it in the H file and implementing in the cpp file. maybe i got the syntax wrong? in the H file i have in "public":

operator int();

and in the cpp file i have:

A::operator int() { return mNumber ;}

if i implement the function in the H file it works, but i don't want to do that.
can anyone help?

like image 733
bks Avatar asked Jun 10 '10 15:06

bks


People also ask

How do I create a header file in cpp?

You make the declarations in a header file, then use the #include directive in every .cpp file or other header file that requires that declaration. The #include directive inserts a copy of the header file directly into the .cpp file prior to compilation.

What is type conversion in C++ with example?

In the program, we have assigned an int data to a double variable. num_double = num_int; Here, the int value is automatically converted to double by the compiler before it is assigned to the num_double variable. This is an example of implicit type conversion.

What is a conversion operator in cpp?

Conversion Operators in C++ C++ supports object oriented design. So we can create classes of some real world objects as concrete types. Sometimes we need to convert some concrete type objects to some other type objects or some primitive datatypes. To make this conversion we can use conversion operator.

What goes in a header file vs cpp file?

The short answer is that a . h file contains shared declarations, a . cpp file contains definitions and local declarations. It's important that you understand the difference between declarations and definitions.


1 Answers

I also wanted to separate the class declaration from the implementation. The critical missing ingredient was the const:

// Foobar.hpp
class Foobar
{
    public:
        Foobar() : _v(42) {}

        operator int() const;

    private:

        int _v;
};

And then in the implementation file:

#include "Foobar.hpp"

Foobar::operator int() const
{
    return _v;
}

See this reference

like image 76
Nick Avatar answered Oct 06 '22 21:10

Nick