使用用户定义的类型转换对象

发布于 2024-12-09 01:08:08 字数 280 浏览 7 评论 0原文

我们可以像处理普通数据类型一样使用用户定义类型强制转换对象吗? 就像我们对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

执手闯天涯 2024-12-16 01:08:08

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.

过潦 2024-12-16 01:08:08

用户定义类型强制转换 为用户类型定义强制转换运算符()。

前任。)

#include <iostream>
#include <cmath>

using namespace std;

struct Point {
    int x;
    int y;
    Point(int x, int y):x(x), y(y){}
    operator int(){
        return sqrt(x*x+y*y);
    }
};

int main() {
    Point point(10,10);
    int x = (int)point;
    cout << x ;
}

user defined type cast defined cast operator() for user type.

ex.)

#include <iostream>
#include <cmath>

using namespace std;

struct Point {
    int x;
    int y;
    Point(int x, int y):x(x), y(y){}
    operator int(){
        return sqrt(x*x+y*y);
    }
};

int main() {
    Point point(10,10);
    int x = (int)point;
    cout << x ;
}
北凤男飞 2024-12-16 01:08:08

你为什么要这样做?我想如果你想创建类的对象,你应该编写适当的构造函数。如您所知,构造函数可以重载。因此,如果您需要以不同的方式构造对象,请随意编写多个构造函数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文