繁体   English   中英

用于隐式类型转换的C ++构造函数

[英]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() ,它然后编译,并使用转换构造函数。 如果我也从mainb的声明中删除const ,那么它更喜欢转换运算符。

这一切都符合重载决策规则。 当gcc无法在转换运算符和转换构造函数之间进行选择时,gcc会生成适当的歧义错误。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM