我为我的应用程序定义了三个类:(int2_
整数对)、float2_
(浮点数对)和double2_
(双精度数对),本质上是为了执行复杂的算术运算。
我想重载=
上述三个类的对象之间的赋值运算符。动机是我正在编写一个 CUDA 代码,但似乎没有为 CUDAint2
类float2
和double2
.
我目前的实现如下:
class int2_ {
public:
int x;
int y;
int2_() : x(), y() {}
// Stuff
const int2_& operator=(const float2_ a) { int2_ b; b.x = (int)a.x; b.y = (int)a.y; return b; }
const int2_& operator=(const double2_ a) { int2_ b; b.x = (int)a.x; b.y = (int)a.y; return b; }
};
class float2_ {
public:
float x;
float y;
float2_() : x(), y() {}
// Stuff
const float2_& operator=(const double2_ a) { float2_ b; b.x = (float)a.x; b.y = (float)a.y; return b; }
};
class double2_ {
public:
double x;
double y;
double2_() : x(), y() {}
// Stuff
};
一切都被总结为不提供编译错误的东西。剩余的运算符重载返回以下错误
error : identifier "float2_" is undefined
error : identifier "double2_" is undefined
error : identifier "double2_" is undefined
分别针对三种不同的重载。
似乎存在“可见性”问题,例如,float2_
并且double2_
在类定义之前尚未int2_
定义。关于如何解决问题的任何建议?非常感谢您提前。
遵循 James KANZE 和 ALEXRIDER 答案的解决方案
这是解决方案:
class int2_;
class float2_;
class double2_;
class int2_ {
public:
int x;
int y;
int2_() : x(), y() {}
inline const int2_& operator=(const int a) { x = a; y = 0.; return *this; }
inline const int2_& operator=(const float a) { x = (int)a; y = 0.; return *this; }
inline const int2_& operator=(const double a) { x = (int)a; y = 0.; return *this; }
inline const int2_& operator=(const int2_ a) { x = a.x; y = a.y; return *this; }
inline const int2_& operator=(const float2_ a);
inline const int2_& operator=(const double2_ a);
};
class float2_ {
public:
float x;
float y;
float2_() : x(), y() {}
inline const float2_& operator=(const int a) { x = (float)a; y = 0.; return *this; }
inline const float2_& operator=(const float a) { x = a; y = 0.; return *this; }
inline const float2_& operator=(const double a) { x = (float)a; y = 0.; return *this; }
inline const float2_& operator=(const int2_ a) { x = (float)a.x; y = (float)a.y; return *this; }
inline const float2_& operator=(const float2_ a) { x = a.x; y = a.y; return *this; }
inline const float2_& operator=(const double2_ a);
};
class double2_ {
public:
double x;
double y;
double2_() : x(), y() {}
inline const double2_& operator=(const int a) { x = (double)a; y = 0.; return *this; }
inline const double2_& operator=(const float a) { x = (double)a; y = 0.; return *this; }
inline const double2_& operator=(const double a) { x = a; y = 0.; return *this; }
inline const double2_& operator=(const int2_ a) { x = (double)a.x; y = (double)a.y;return *this; }
inline const double2_& operator=(const float2_ a) { x = (double)a.x; y = (double)a.y;return *this; }
inline const double2_& operator=(const double2_ a) { x = a.x; y = a.y; return *this; }
};
inline const int2_& int2_::operator=(const float2_ a) { x = (int)a.x; y = (int)a.y; return *this; }
inline const int2_& int2_::operator=(const double2_ a) { x = (int)a.x; y = (int)a.y; return *this; }
inline const float2_& float2_::operator=(const double2_ a) { x = (float)a.x; y = (float)a.y; return *this; }