[英]C++ Constructor for Implicit Type Conversion
我有這些代碼:
class Type2 {
public:
Type2(const Type1 & type);
Type2(int);
const Type2 & operator=(const Type2 & type2);
//....
};
...
Type1 t1(13);
Type2 t2(4);
t2=t1;
據我所知,Type2的1參數構造函數都沒有顯式關鍵字,這意味着任何Type1對象或int值都可以隱式地傳遞給Type2對象。
但在最后一行t2 = t1; ,MS Visual Studio給我這個編譯錯誤:
....錯誤C2679:二進制'=':沒有找到哪個操作符采用'Type1'類型的右操作數(或者沒有可接受的轉換)....
好像MS Visual Studio堅持t2 = t1; 必須匹配賦值運算符lhs = Type2和rhs = Type1。 為什么不能將rhs隱式地轉換為t2然后使用Type2 = Type2運算符進行復制?
我找到了答案。 因為我的Type1有一個轉換運算符
class Type1 {
public:
Type1 (int );
operator Type2() ;//casting to Type2
....
};
這就是所謂的“雙向隱式轉換”
這段代碼:
#include <iostream>
using ::std::cerr;
class Barney;
class Fred {
public:
Fred() { }
Fred(const Barney &b) { cerr << "Using conversion constructor.\n"; }
};
class Barney {
public:
Barney() { }
operator Fred() const { cerr << "Using conversion operator.\n"; return Fred(); }
};
int main(int argc, const char *argv[])
{
const Barney b;
Fred f;
f = b;
return 0;
}
在gcc 4.6中生成此錯誤:
g++ -O3 -Wall fred.cpp -o a.out
fred.cpp: In function ‘int main(int, const char**)’:
fred.cpp:23:8: error: conversion from ‘const Barney’ to ‘const Fred’ is ambiguous
fred.cpp:21:17: note: candidates are:
fred.cpp:16:4: note: Barney::operator Fred() const
fred.cpp:10:4: note: Fred::Fred(const Barney&)
fred.cpp:7:7: error: initializing argument 1 of ‘Fred& Fred::operator=(const Fred&)’
Compilation exited abnormally with code 1 at Sun Jun 19 04:13:53
現在,如果我刪除const
after operator Fred()
,它然后編譯,並使用轉換構造函數。 如果我也從main
中b
的聲明中刪除const
,那么它更喜歡轉換運算符。
這一切都符合重載決策規則。 當gcc無法在轉換運算符和轉換構造函數之間進行選擇時,gcc會生成適當的歧義錯誤。
我注意到在你給出的例子中,轉換運算符缺少一個const
。 這意味着永遠不會出現使用轉換運算符或轉換構造函數不明確的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.