2011-06-19 53 views
3

我有这些代码:C++构造隐式类型转换

class Type2 { 
public: 
    Type2(const Type1 & type); 
    Type2(int); 
const Type2 & operator=(const Type2 & type2); 
//.... 
}; 

... 
    Type1 t1(13); 
    Type2 t2(4); 

    t2=t1; 

正如我理解,每个第二类型的1参数构造没有明确关键字应该是指任何类型1的对象或者int值可以是隐式传达给Type2物体。

但在最后一行t2 = t1;,MS Visual Studio中给了我这个编译错误:

....error C2679: binary '=' : no operator found which takes a right-hand operand of type 'Type1' (or there is no acceptable conversion)....

好像MS Visual Studio中坚持T2 = T1;必须与lhs = Type2和rhs = Type1的赋值运算符匹配。为什么不能将rhs隐式转换为t2,然后使用Type2 = Type2运算符进行复制?

+0

这段代码在VS2010中编译得很好。 –

+0

我知道为什么。因为我的Type1有一个转换运算符:class Type1 {operator Type2()}; – JavaMan

+0

我可以关闭一个我自己找到答案的问题吗? – JavaMan

回答

2

我找到了答案。因为我的类型1有一个转换操作符

class Type1 { 
    public: 
     Type1 (int); 
     operator Type2() ;//casting to Type2 

    .... 
    }; 

这是一种叫“双向隐式转换”

+0

有趣。这在GCC中编译得很好。 –

+0

是的,即使VS2010有时也会编译。但我必须弄清楚什么时候。这是编译器无法知道应该使用哪种转换的标准模糊情况。恕我直言,他们应该产生编译时错误。 – JavaMan

+0

@Oli什么编译?我看到有很多'...'的代码片段 –

1

此代码:

#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 

现在,如果我删除0123在operator Fred()之后的,它然后编译并使用转换构造函数。如果我还从main中的b声明中删除const,则它将优先选择转换运算符。

这一切都符合重载解析规则。当gcc无法在转换操作符和转换构造器之间进行选择时,gcc会生成适当的模糊性错误。

我注意到在你给的例子中,转换操作符缺少const。这意味着永远不会存在使用转换运算符或转换构造函数不明确的情况。