将 int 转换为类指针?
我正在尝试创建从 A*
到 int 的强制转换,其中 A
是我定义的类。
如果您想知道的话,转换来自查找(int 是该 A 实例的 id)。
目前,我有:
#include <iostream>
class A{
private:
int val;
public:
A(){};
A(int val): val(val){};
static A* cast(int val){
return &(A());
//This will actually be a valid pointer
}
explicit operator int(){
return val;
}
};
int main() {
A a(7);
std::cout << "Pointer: " << &a << std::endl;
std::cout << "Pointer cast: " << A::cast(5) << std::endl; //would like this to be static_cast<A*>(5)
std::cout << "Int cast: " << static_cast<int>(a) << std::endl;
}
我可以创建一个从 A
到 int
的漂亮转换。但是,我无法弄清楚如何定义从 A*
到 int
的转换,反之亦然。
注意:我目前将此作为 A
类中的函数使用,但在我的用例中,强制类型转换会感觉更自然。
I am trying to create a cast from A*
to int where A
is a class I've defined.
The conversion is from a lookup, (the int is the id of that A instance) in case you wanted to know.
Currently, I have:
#include <iostream>
class A{
private:
int val;
public:
A(){};
A(int val): val(val){};
static A* cast(int val){
return &(A());
//This will actually be a valid pointer
}
explicit operator int(){
return val;
}
};
int main() {
A a(7);
std::cout << "Pointer: " << &a << std::endl;
std::cout << "Pointer cast: " << A::cast(5) << std::endl; //would like this to be static_cast<A*>(5)
std::cout << "Int cast: " << static_cast<int>(a) << std::endl;
}
I can create a nice cast from A
to int
. However, I cannot figure out how to define the casts for A*
to int
and vice versa.
Note: I currently have this working as a function in the A
class, but a cast-style conversion would feel more natural in my use case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论