您的位置:首页 > 其它

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

2014-11-02 19:11 148 查看
一、自动转换

1、通过构造函数来实现

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

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

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

1、转换函数原型:

operator typeName();

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

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

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

#ifndef WEIGHT_H
#define WEIGHT_H

class 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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: