I created a user-defined literal like this, in is OWN .cpp
file (declared as a friend
function in .h
file):
fraction operator"" _frac(const long double val)
{
return fraction(static_cast<float>(val));
}
But in main
it produces this error:
Error (active)E2486 user-defined literal operator not found
But, when I write the SAME code (definitely the same, as I copy it, and also do some words comparison) in main
or .h
(outside of the class scope) file, it works fine, why?
I'm using Visual Studio 2019 and C++20 (GitHub Files).
Test.h
:
#pragma once
class test
{
double x;
public:
explicit test(const double a) : x(a) {};
friend test operator "" _t(long double a);
};
Test.cpp
:
#include "Test.h"
test operator "" _t(const long double a)
{
return test(a);
}
main
:
#include "Test.h"
int main()
{
test t = 12_t; //error
}
Yes, I know that this is due to the fact that it doesn't have a parameter which is a class, which makes it internal to the class. I want to ask how to declare this in the .cpp
file but still be acessible from main
(declaration and friend keywords in .h
doesn't matter).
I created other classes, and use an older version of C++, I still get the same result (definition in the same file as main
works fine, but if written in another file it doesn't work). I can accept to write it in the same file, but then what's the purpose of orientated programming anymore?
Using the extern
keyword can help, but my compiler doesn't like it, and it's also very inconvenient every time I have to write that in main
.
The user-defined literal function just is not declared in your main.cpp
.
Place
test operator "" _t(const long double a);
in your test.h