类的自动转换和强制类型转换

来源:互联网 发布:中信建投期货软件 编辑:程序博客网 时间:2024/05/28 16:14

一、自动转换

1、通过构造函数来实现

2、支持隐式转换,如果构造函数前使用explicit关键字,将关闭隐式转换

3、实现了将其他数据类型转换为类

二、强制类型转换——转换函数

1、转换函数原型:

operator typeName();

typeName为要转换的类型,如int,double。。。

2、注意隐式转换时避免二义性

3、实现了将类转换为其他数据类型


#ifndef WEIGHT_H#define WEIGHT_Hclass Weight{    public:        Weight(double kg = 0);        ~Weight();        double getWeight() const;        operator int() const;  //转化函数 class to int    protected:    private:        double kg;};#endif // WEIGHT_H
weight.cpp

#include "Weight.h"Weight::Weight(double kg){    this->kg = kg;}Weight::~Weight(){    //dtor}double Weight::getWeight() const{    return kg;}Weight::operator int() const{    return int(kg);}
main.cpp

#include <iostream>#include "Weight.h"using namespace std;int main(){    Weight weightTest;    weightTest = 3.4;  //implicit ,  weightTest = (Weight)3.2  cast number to class    int num = weightTest; //implicit ,  num = (int)weightTest  cast class to number    cout << "weightTest"<<(double)weightTest << endl;    cout <<"num = "<<num<<endl;    return 0;}



0 0