C++ Primer Plus学习:第十一章 使用类(3)

本文探讨了类构造函数的使用,特别是如何利用转换函数将不同类型的对象转换为类类型,通过实例展示了如何实现自动转换和强制转换,并在代码中提供了具体的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类的自动转换和强制转换
  只有一个参数的类构造函数用于将类型与该参数相同中的值转换为类类型
  被称为转换函数的特殊类成员操作符函数,用于将类对象转换为其他类型
  eg

    stonewt1.h

#ifndef STONEWT1_H_
#define STONEWT1_H_
class Stonewt
{
      private:
              enum{Lbs_per_stn = 14};
              int stone;
              double pds_left;
              double pounds;
      public:
             Stonewt(double lbs);
             Stonewt(int stn,double lbs);
             Stonewt();
             ~Stonewt();
             void show_lbs()const;
             void show_stn()const;
             //conversion functions
             operator int()const;
             operator double()const;
      };
#endif


    stone1.cpp

#include <iostream>
using std::cout;
#include "stonewt1.h"

int main()
{
    //调用 Stonewt(int stn,double lbs) 
    Stonewt popins(9,2.8);
    double p_wt = popins;
    cout<<"Convert to double => ";
    cout<<"Popins: "<<p_wt<<" pounds.\n";
    cout<<"Convert to int => ";
    cout<<"Popins: "<<int(popins)<<" pounds.\n";
    
    system("pause");
    return 0;
    }
    


    stonewt2.cpp

#include <iostream>
using std::cout;
#include "stonewt1.h"

Stonewt::Stonewt(double lbs)
{
                        stone = int(lbs)/Lbs_per_stn;
                        pds_left = int(lbs)%Lbs_per_stn + lbs - int(lbs);
                        pounds = lbs;
                        }
                        
Stonewt::Stonewt(int stn,double lbs)
{
                     stone = stn;
                     pds_left = lbs;
                     pounds = stn*Lbs_per_stn + lbs;
                     }

Stonewt::Stonewt()
{
                  stone = pounds = pds_left = 0;
                  }
                  
Stonewt::~Stonewt()
{
                   }
                   
void Stonewt::show_stn()const
{
     cout<<stone<<" stone, "<<pds_left<<" pounds\n";
     }
     
void Stonewt::show_lbs()const
{
     cout<<pounds<<" pounds\n";
     }

Stonewt::operator int()const
{
                  return int(pounds + 0.5);
                  }
                  
Stonewt::operator double()const
{
                  return pounds;
                  }


main()函数之前调用Bootstrap
  全局对象(有文件作用域的对象)可实现
  全局对象将在程序的main()函数被调用之前创建
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值