面向对象程序设计(三):C++模板operator Type类型转换


学习算法的时候遇到了一个不认识的写法,去网上查了查,看到有一篇写的挺好的,转载过来了

C++隐式类型转换运算符operator type()用法详解

对象向基本数据类型转换:
点击查看代码
#include
#include
using namespace std;
  
class D{
public:
  D(double d):d_(d) {}
  operator int() const{
    std::cout<<"(int)d called!"<(d_);
  }
private:
  double d_;
};
  
int add(int a,int b){
  return a+b;
}
  
int main(){
  D d1=1.1;
  D d2=2.2;
  std::cout<
对象向不同类的对象的转换:
点击查看代码
#include
class X;
class A
{
public:
  A(int num=0):dat(num) {}
  A(const X& rhs):dat(rhs) {}
  operator int() {return dat;}
private:
  int dat;
};
  
class X
{
public:
  X(int num=0):dat(num) {}
  operator int() {return dat;}
  operator A(){
    A temp=dat;
    return temp;
  }
private:
  int dat;
};
  
int main()
{
 X stuff=37;
 A more=0;
 int hold;
 hold=stuff;
 std::cout<