编译器如何选择自动类型转换方法 [英] how does the compiler choose automatic type conversion method

查看:290
本文介绍了编译器如何选择自动类型转换方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码中,使用两种方法允许将Y对象转换为X对象。编译通过g ++总是选择构造函数。如果构造函数是私有的,像:

private:Y(const X&){std :: cout< Y constructor ... \\\
; }


转换由操作员或构造函数阻止。如果构造函数是私有和显式的

private:explicit Y(const X&){std :: cout< Y constructor ... \\\
; }


编译器改用操作符。是通过使转换构造函数私有还是编译器用于进行这种转换的规则来阻止自动转换的通常方式。

In this code, two methods were used to allow conversion of Y object into X object. compiling by g++ always choose constructor. if constructor is private like :
private : Y(const X&){std::cout << "Y constructor...\n" ; }
conversion is prevented either by operator or constructor. if constructor is private and explicit
private : explicit Y(const X&){std::cout << "Y constructor...\n" ; }
compiler use operator instead. Is it the usual way to prevent auto conversion by making conversion constructor private and what is the rule that compiler use to make such kind of conversion.

#include <iostream>

class Y ;

class X {
public:
  operator Y()const ;
};

class Y {
public:
  Y(){}
private : 
  explicit Y(const X&){std::cout << "Y constructor...\n" ; }
};

X::operator Y() const { std:: cout << "Operator Y...\n" ;
 return Y ();
}


void func(Y Y_object) {}

int main() {
  X X_object ;
  Y Y_object ;

  func(X_object) ;
  Y_object = X_object ;
}


推荐答案

隐式类型转换不是要声明转换操作符,而是使构造函数显式。但是,如果要保留转换运算符,则可以使用显式关键字来明确:

The most usual way to prevent implicit type conversion is not to declare conversion operator at all and make the constructor explicit. However, if you want to keep the conversion operator, you can make explicit too using explicit keyword:

class X {
public:
  explicit operator Y() const;
};

这篇关于编译器如何选择自动类型转换方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆