![](/img/trans.png)
[英]Is there a default explicit conversion function for user-defined class (c++)?
[英]Explicit cast from int to a user defined class, c++
我如何啟用從int到用戶定義的類Foo的顯式轉換?
我做了一個從int到Foo的轉換構造函數,但這是嗎? 我可以重載從Foo到int的強制轉換運算符,但這不是我想要的。
有沒有辦法啟用這段代碼?
int i = 5;
Foo foo = (Foo)i;
閱讀有關轉換構造函數的信息 。
如果您不將構造函數設置為explicit
,則可以將類型(構造函數接受)轉換為(新構造的)類實例。
這是例子
#include <iostream>
template<typename T>
class Foo
{
private:
T m_t;
public:
Foo(T t) : m_t(t) {}
};
int main()
{
int i = 0;
Foo<int> intFoo = i;
double d = 0.0;
Foo<double> doubleFoo = d;
}
像這樣:
struct Foo {
explicit Foo(int x) : s(x) { }
int s;
};
int main() {
int i = 5;
Foo foo =(Foo)i;
}
您需要一個接受int
的構造函數
class Foo {
public:
Foo (int pInt) {
....
}
Foo (double pDouble) {
....
}
int i = 5;
Foo foo(i); // explicit constructors
Foo foo2(27);
Foo foo3(2.9);
Foo foo4 = i; // implicit constructors
Foo foo5 = 27;
Foo foo6 = 2.1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.