实现指针转换操作符
Implement conversion operator for pointer
这个问题很简单,但是我找不到解决办法。
class foo
{
public:
operator int()
{
return 5;
}
};
foo* a = new foo();
int b = a;
有可能实现这种行为吗?
你不能。转换操作符需要是类的成员,但foo*
不是用户定义的类类型,它是指针类型(此外,int b = *a
也可以)。
你能做的最好的事情是使用一个实用函数来进行强制转换。
可以,通过显式调用操作符:
foo* a = new foo();
int b = a->operator int();
相关文章:
- 我可以将C 17 Capture lambda ConstexPR转换操作符的结果用作函数指针模板非类型参数吗?
- Clang vs GCC vs MSVC模板转换操作符-哪个编译器是正确的
- 为什么操作符的新函数需要强制转换
- c++中从整数到字符串的转换中,左移操作符是做什么的?
- 模板类型转换操作符=
- 链接隐式转换操作符
- 强制转换操作符函数在g++中可以很好地编译,但在其他编译器中不行.为什么
- 当目标类有多个构造函数时,消除强制转换操作符的歧义
- 删除转换操作符
- 强制转换操作符重载和引用
- 实现没有临时的转换操作符
- 不同的强制转换操作符被不同的编译器调用
- 将操作符转换为模板实参的特化
- 为什么模板化的用户定义转换操作符能够确定其返回类型?
- const转换操作符
- 在可强制转换为另一个模板类型的类模板中重载赋值操作符
- 调用转换操作符不能用于静态const变量
- 内部编译器错误-开关表达式中的模板化转换操作符
- 强制转换操作符可以是显式的吗?
- 在返回语句中统一初始化,并显式将操作符转换为bool