C ++中的用户定义的转换 [英] User Defined Conversions in C++

查看:112
本文介绍了C ++中的用户定义的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我浏览了来自O'Reilly Media的 C ++ Pocket Reference 的副本,当我遇到一个关于用户定义转换的简短章节和示例时,定义的类型:

Recently, I was browsing through my copy of the C++ Pocket Reference from O'Reilly Media, and I was surprised when I came across a brief section and example regarding user-defined conversion for user-defined types:

#include <iostream>

class account {

    private:
        double balance;

    public:
        account (double b) { balance = b; }

        operator double (void) { return balance; }
};

int main (void) {

    account acc(100.0);
    double balance = acc;

    std::cout << balance << std::endl;

    return 0;
}



我已经在C ++中编程了一段时间,这是第一次我见过这种操作符重载。这本书对这个主题的描述有点简短,让我对这个功能有几个未解答的问题:

I've been programming in C++ for awhile, and this is the first time I've ever seen this sort of operator overloading. The book's description of this subject is somewhat brief, leaving me with a few unanswered questions about this feature:


  • 这是一个特别模糊的功能吗?正如我所说,我已经在C ++中编程了一段时间,这是我第一次遇到这个。我没有太多运气找到更深入的材料关于这一点。

  • 这是相对便携吗? (我在GCC 4.1上编译)

  • 用户定义的转换是否可以完成用户定义的类型?例如

  • Is this a particularly obscure feature? As I said, I've been programming in C++ for awhile and this is the first time I've ever come across this. I haven't had much luck finding more in-depth material regarding this.
  • Is this relatively portable? (I'm compiling on GCC 4.1)
  • Can user-defined conversions to user defined types be done? e.g.

运算符std :: string(){/ * code * /}

operator std::string () { /* code */ }

推荐答案


这是一个特别模糊的功能吗?

Is this a particularly obscure feature?


$ b b

是的,转换运算符不常使用。我看到的地方是用户定义的类型,可以降级为内置的。

Yes, conversion operators aren't used very often. The places I've seen them are for user-defined types that can degrade to built-in ones. Things like a fixed-precision number class that supports converting to/from atomic number types.


这是相对可移植的吗?

Is this relatively portable?

据我所知,它是。


是否可以执行用户定义的用户定义类型的转换?

Can user-defined conversions to user defined types be done?

是的,这是构造函数的一个特性。接受单个参数的构造函数有效地创建从参数类型到类的类型的转换运算符。例如,这样的类:

Yes, that's one of the features of constructors. A constructor that takes a single argument effectively creates a conversion operator from the argument type to your class's type. For example, a class like this:

class Foo {
public:
    Foo(int n) {
        // do stuff...
    }
}

让你做:

Foo f = 123;

如果您使用 std :: string 之前,赔率是你使用这个功能,而没有意识到。 (另外,如果你想阻止这种行为,使用 explicit 声明任何单参数构造函数。)

If you've used std::string before, odds are you've used this feature without realizing it. (As an aside, if you want to prevent this behavior, declare any single-argument constructors using explicit.)

这篇关于C ++中的用户定义的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆