有没有办法将转换运算符添加到基本类型?
例如:
Someclass x = (Someclass)7; //or even implicit casting
我知道可以在someclass
中创建一个接受int的ctor,但有没有办法将转换运算符添加到int?
答案 0 :(得分:2)
您的示例代码
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";
}
没有构造函数:
#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";
}
如果您要问&#34;如何使用转换运算符将int转换为SomeClass&#34;最接近的是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";
}
答案 1 :(得分:2)
不,那是不可能的。您无法更改基本(内置)类型的操作。