使用用户定义的类型转换对象
我们可以像处理普通数据类型一样使用用户定义类型强制转换对象吗? 就像我们对 int 进行类型转换一样:
int variable_one = (int)variable_name;
那么我们可以这样做: (complex) object_name;
其中complex是我使用operator+
重载为复数加法编写的类。
用这种正常的方式可以吗?或者我们需要在调用这个语句之前编写一些函数吗?或者根本不可能像这样进行类型转换?
Can we cast an object with user-defined types, like we do for normal data types?
Like say we do type cast for int like:
int variable_one = (int)variable_name;
So can we do like: (complex) object_name;
where complex is the class I have written for complex number addition using operator+
overloading.
Is it possible in this normal way? Or do we need to write some function before calling this statment? Or is it not possible at all to type-cast like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
int variable_one=(int)variable_name;
是 C 风格的强制转换。C++ 提供了许多转换运算符:
dynamic_cast; (表达式)
reinterpret_cast; (表达式)
static_cast; (表达式)
const_cast; (表达式)
查看有关类型转换的文章或参考任何 C++ 入门书籍。
int variable_one=(int)variable_name;
is a C style cast.C++ offers many casting operators:
dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression)
const_cast <new_type> (expression)
Have a look at article about type casting or refer to any C++ introductory book.
用户定义类型强制转换 为用户类型定义强制转换运算符()。
前任。)
user defined type cast defined cast operator() for user type.
ex.)
你为什么要这样做?我想如果你想创建类的对象,你应该编写适当的构造函数。如您所知,构造函数可以重载。因此,如果您需要以不同的方式构造对象,请随意编写多个构造函数。
Why you want to do this? I guess you should write appropriate constructors if you want to create an object of your class. As you know, the constructors can be overloaded. So feel free to write more than one constructor if you need your objects to be constructed in different ways.