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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With