c++ - 有没有办法向原始类型添​​加转换运算符?

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

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

例如:

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

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

最佳答案

您的示例代码

SomeClass x = (SomeClass)7;

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

struct SomeClass {
    SomeClass(int) {}
};

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

如果您希望能够将 SomeClass 转换为整数,则需要运算符 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

关于c++ - 有没有办法向原始类型添​​加转换运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35186919/

相关文章:

javascript - 在 JavaScript 中显示文本文件

C++ 错误 STATUS_ACCESS_VIOLATION

java - 无法解密用Java加密的消息

multithreading - magic statics : similar constructs, 有趣的非显而易见的用途?

objective-c - 为什么不能将 ivar 的地址传递给 ARC 下的 "id __autoreleasing *"参数?

php - 在 PHP 中使用 `new ClassName` 和 `new ClassName()` 创建对象的区别

c++ - 静态变量释放顺序

c++ - OpenCL/C++ - 返回一个 cl::Buffer 对象

C++ u8 literal char 覆盖

c++ - 如何初始化没有默认构造函数的对象成员 std::array?