是否可以在对象上定义自定义铸造成为方法调用的结果?

发布于 2025-01-30 22:32:49 字数 161 浏览 3 评论 0原文

是否可以在对象上定义自定义铸造,以使对象铸造为方法调用结果?

class Foo {
  public:
    ...
    int method() { return 3; }
};

Foo foo;
int bar = foo + 7; // 10

Is it possible to define a custom cast on an object so that the objects casts to the result of a method call?

class Foo {
  public:
    ...
    int method() { return 3; }
};

Foo foo;
int bar = foo + 7; // 10

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

神爱温柔 2025-02-06 22:32:49

您可以提供转换函数如下所示:

方法1

直接在转换功能内使用int而无需使用方法

class Foo {
  public:
    //conversion function
    operator int()
    {
        return 3;
    }
};

Foo foo;
int bar = foo + 7; // bar is initialized with 10

int main()
{
    std::cout<<bar;//prints 10
    return 0;
}

demo

方法2

使用方法返回int int 从转换功能内部。

class Foo {
  public:
    
    int method() { return 3; }
    
    operator int()
    {
        return method();
    }
};

Foo foo;
int bar = foo + 7; // 10

int main()
{
    std::cout<<bar;//prints 10
    return 0;
}

You could provide a conversion function as shown below:

Method 1

Directly return an int without using method inside the conversion function.

class Foo {
  public:
    //conversion function
    operator int()
    {
        return 3;
    }
};

Foo foo;
int bar = foo + 7; // bar is initialized with 10

int main()
{
    std::cout<<bar;//prints 10
    return 0;
}

Demo

Or

Method 2

Use method to return an int from inside the conversion function.

class Foo {
  public:
    
    int method() { return 3; }
    
    operator int()
    {
        return method();
    }
};

Foo foo;
int bar = foo + 7; // 10

int main()
{
    std::cout<<bar;//prints 10
    return 0;
}
宛菡 2025-02-06 22:32:49

AGH。我过度想到了。

#include <iostream>
#include <string>

class Foo {
    public:
    Foo() { _data = 3; }
    int method() { return _data; }
    operator int() {
        return method();
    }
    int _data;
};

int main()
{
  Foo foo;
  int bar = foo + 7;
  std::cout << bar << std::endl;
}

Agh. I was overthinking it.

#include <iostream>
#include <string>

class Foo {
    public:
    Foo() { _data = 3; }
    int method() { return _data; }
    operator int() {
        return method();
    }
    int _data;
};

int main()
{
  Foo foo;
  int bar = foo + 7;
  std::cout << bar << std::endl;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文