【问题标题】:Is there a way to add conversion operators to primitive types?有没有办法将转换运算符添加到原始类型?
【发布时间】:2016-02-03 20:20:59
【问题描述】:

有没有办法将转换运算符添加到原始类型?

例如:

Someclass x = (Someclass)7; //or even implicit casting

我知道可以在someclass 中创建一个接受 int 的 ctor,但是有没有办法将转换运算符添加到 int 中?

【问题讨论】:

  • 不,那是不可能的
  • 如果 SomeClass 有一个采用 int 的构造函数,则您提供的代码将编译。 “有没有办法将转换运算符添加到 int ”没有意义,除非你的意思是“我想做int x = SomeClass c;”
  • @CaptainGiraffe 你错过了“我知道可以在某个接受 int 的类中创建一个 ctor,但是有没有办法将转换运算符添加到 int 中?”
  • @DieterLücking 是的,我被示例代码行甩了。

标签: c++ c++11 syntax casting operator-overloading


【解决方案1】:

您的示例代码

SomeClass x = (SomeClass)7;

如果 SomeClass 有一个接受 int 的构造函数,则编译:

struct SomeClass {
    SomeClass(int) {}
};

int main() {
    SomeClass x = (SomeClass)7;
}

如果您希望能够将 SomeClass 转换为整数,则需要 operator int()

#include <iostream>

class SomeClass {
    int m_n;

public:
    SomeClass(int n_) : m_n(n_) {}
    SomeClass() : m_n(0) {}

    operator int () { return m_n; }
};

int main() {
    SomeClass x = 7; // The cast is not required.
    std::cout << (int)x << "\n";
}

现场演示:http://ideone.com/fwija0

没有构造函数:

#include <iostream>

class SomeClass {
    int m_n;

public:
    SomeClass() : m_n(123) {}

    operator int () { return m_n; }
};

int main() {
    SomeClass x;
    std::cout << (int)x << "\n";
}

http://ideone.com/xfsdjp

如果您问“如何使用转换运算符将 int 转换为 SomeClass”,最接近的是 operator=

#include <iostream>

class SomeClass {
public:
    int m_n;
    SomeClass() : m_n(0) {}
    SomeClass& operator = (int n) { m_n = n; return *this; }
};

int main() {
    SomeClass sc;
    std::cout << "sc.m_n = " << sc.m_n << "\n";
    sc = 5;
    std::cout << "sc.m_n = " << sc.m_n << "\n";
}

http://ideone.com/wDl4oP

【讨论】:

  • 我不会容忍使用operator int,因为它是到int 的隐式转换,可以在许多不受欢迎的情况下调用。我认为这不是 OP 所要求的,但 explicit operator int 将是更安全的继续方式。
  • 如您所见,here 不需要 &lt;&lt; (int) x 演员表,但 here 演员表是必需的。
  • 从不进行类型的隐式转换 - 使构造函数或运算符 T 显式
  • 我问如果没有接受 int 的 ctor,这是否可能。
  • @kuhaku 您是否要求将 从 int 转换为 SomeClass 的转换运算符?你可以写一个'operator=(int)'。
【解决方案2】:

不,那是不可能的。您不能更改原始(内置)类型的操作。

【讨论】:

    猜你喜欢
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 2022-06-18
    • 1970-01-01
    相关资源
    最近更新 更多