你能在 OOP 中"超载演员表"C++吗?
Can you 'overload a cast' in C++ OOP?
好吧,winapi具有POINT
结构,但是我正在尝试为此做一个替代类,以便您可以从构造函数设置x
和y
的值。这很难用一个句子解释。
/**
* X-Y coordinates
*/
class Point {
public:
int X, Y;
Point(void) : X(0), Y(0) {}
Point(int x, int y) : X(x), Y(y) {}
Point(const POINT& pt) : X(pt.x), Y(pt.y) {}
Point& operator= (const POINT& other) {
X = other.x;
Y = other.y;
}
};
// I have an assignment operator and copy constructor.
Point myPtA(3,7);
Point myPtB(8,5);
POINT pt;
pt.x = 9;
pt.y = 2;
// I can assign a 'POINT' to a 'Point'
myPtA = pt;
// But I also want to be able to assign a 'Point' to a 'POINT'
pt = myPtB;
是否可以以某种方式过载operator=
,以便我可以将Point
分配给POINT
?或者也许还有其他实现此目标的方法?
这是类型转换操作员的作业:
class Point {
public:
int X, Y;
//...
operator POINT() const {
POINT pt;
pt.x = X;
pt.y = Y;
return pt;
}
};
您可以在Point
类中添加铸件运算符:
class Point {
// as before
....
operator POINT () const {
// build a POINT from this and return it
POINT p = {X,Y};
return p;
}
}
使用转换操作员:
class Point
{
public:
operator POINT()const
{
Point p;
//copy data to p
return p;
}
};
相关文章:
- 寻找地理和伤害意味着超载
- 没有可行的超载'='用于shared_ptr
- "专业化不参与超载"
- 虚拟超载运算符>>和<<
- 为什么我的超载"+"运算符返回的总额错误?
- C++ 超载 += 用于两个袋子的合并,返回类型为空隙
- C++11 中对超载'ref(Select::Expressions::Code&)'的调用模棱两可
- 为什么STD :: SPAN超载函数调用操作员索引
- C 操作员超载调用驱动器
- C const char *评估操作员超载
- 如何包括C 模板类的非成员运算符 - 超载
- 类型长的长度和未解决的超载函数类型的类型的操作数与二进制运算符
- 无法调用纯抽象基类超载
- 二进制超载操作员=
- 操作员超载;必须是二进制操作员(具有3个参数)
- 如果我具有调用其其他实例之一的超载函数,它是否被认为是递归功能
- 超载 =具有多个术语的运算符
- GLM超载操作员用于地图不起作用
- C bool表达式作为函数参数调用错误的超载
- 运算符超载的Lambda表达式