我有一个 Komp 类,其中我有一个用户定义的文字constexpr Komp operator""_i(long double x)
来从 eg 生成一个 komp 对象Komp k = 1 + 5.0_i;
。
这在komp.cpp的 main() 中工作正常,但是当我在 testing.cpp (其中包括komp.h )中编写相同的确切语句时,我得到以下错误。komp.h中的所有其他功能在testing.cpp中都可以正常工作。我希望像其他函数一样包含用户定义的文字。
为什么用户定义的文字在testing.cpp中不起作用,而其他函数却在起作用?
错误:
Undefined symbols for architecture x86_64:
"operator"" _i(long double)", referenced from:
MyTestSuite::test5() in komp_testrunner-d3c20f.o
ld: symbol(s) not found for architecture x86_64
// komp.cpp
class Komp {
private:
double val1;
double val2;
public:
// ... Bunch of member-function headers
constexpr Komp(const double x, const double y) : val1(x), val2(y) {}
double v1() {return val1;}
double v2() {return val2;}
};
// ... Bunch of member and non-member functions.
Komp operator+ (const double lhs, const Komp rhs) { // overloads + operator for: double + Komp
return Komp(lhs+rhs.v1(), rhs.v2());
}
constexpr Komp operator""_i(long double x) { // To match i.e Komp k = 1 + 2.3_i
return Komp(0.0, x);
}
constexpr Komp operator""_i(unsigned long long x) { // To match i.e Komp k = 1 + 2_i
return Komp(0.0, x*1.0);
}
int main() { // Only here temporarily for testing purposes
Komp k = 1 + 2.0_i; // Works here
}
// komp.h
#include <string>
#ifndef KOMP_H
#define KOMP_H
class Komp
{
public:
double val1;
double val2;
// ...
Komp(const double x, const double y);
};
// ...
Komp operator+ (const double lhs, const Komp rhs);
Komp operator ""_i(long double arg);
Komp operator ""_i(unsigned long long arg);
#endif
#include "komp.h"
#include <cxxtest/TestSuite.h>
class Testing : public CxxTest::TestSuite {
public:
void literalTest () {
Komp c = 3.0 + Komp(2.0, 2.0); // Works fine. No problem with overloading + operator
Komp b = 5.0 + 2.0_i; // Causing an error
Komp c = Komp(1.0, 2.0);
TS_ASSERT(b != c);
}
};