2026/3/14 11:16:51
网站建设
项目流程
做网站有什么要求,树莓派wordpress frp,建设网站的策划书,做外国网站8.类的自动转换和类的强制类型转换在类中定义常量的方式#xff1a;1、enum枚举#xff1b;2、static const int a 14;#xff08;原因参见10.6#xff09;a.类的自动转换(将double#xff0c;int转换为类)构造函数将某种类型转换为类。Stonewt.h#ifndef __STONEWT_H__
#…8.类的自动转换和类的强制类型转换在类中定义常量的方式1、enum枚举2、static const int a 14;原因参见10.6a.类的自动转换(将doubleint转换为类)构造函数将某种类型转换为类。Stonewt.h#ifndef __STONEWT_H__ #define __STONEWT_H__ #include iostream using namespace std; class Stonewt { private: enum { Lbs_per_stn 14 }; int stone; double pds_left; double pounds; public: //explicit Stonewt(double lbs); Stonewt(double lbs); Stonewt(int stn, double lbs); Stonewt(); void show_lbs() const; void show_stn() const; }; #endif .Stonewt.cpp#include stonewt.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 pds_left pounds 0; } void Stonewt::show_stn() const { cout stone stone, pds_left pounds. endl; } void Stonewt::show_lbs() const { cout pounds pounds. endl; } .main.cpp#include iostream #include stonewt.h using namespace std; int main(void) { //将275作为只带一个参数的构造函数的实参 //创建一个临时的Stonewt对象这个对象使用只带一个参数的构造函数来构造参数是275将这个临时的Stonewt对象传递给incognito Stonewt incognito 275; //Stonewt incognito(275); // Stonewt incognito Stonewt(275);//Stonewt(275)创建一个无名的Stonewt类的对象并将这个对象赋值给incognito Stonewt wolfe(285.7); //Stonewt(double ); Stonewt taft(21, 8); incognito.show_stn(); wolfe.show_stn(); taft.show_lbs(); cout ------------------------- endl; incognito 276.8; taft 325; incognito.show_stn(); taft.show_lbs(); return 0; } 将构造函数用作自动类型转换函数似乎是一项不错的特性。然而当程序员拥有更丰富的 C经验时,将发现这种自动特性并非总是合乎需要的,因为这会导致意外的类型转换。因此,C新增了关键字 explicit,用于关闭这种自动特性。也就是说可以这样声明构造函数:explicit stonewt(double lbs);//no implicit conversions allowedb.转换函数构造函数将某种类型转换为类要进行相反的转换必须使用特殊的C运算符函数———转换函数。转换函数时用户定义的强制类型转换可以像使用强制类型转换那样使用它们。Stonewt wolfe(285.7); double host double(wolfe); double thinker (double)wolfe;// syntax #2 // syntax #1 //也可以让编译器来决定如何做: Stonewt wells(20, 3); double star wells; //implicit use of conversion function编译器发现右侧是 Stonewt类型而左侧是 double 类型因此它将查看程序员是否定义了与此匹配的转换函数。(如果没有找到这样的定义编译器将生成错误消息指出无法将 Stonewt赋给 double。)那么如何创建转换函数呢?要转换为typeName类型需要使用这种形式的转换函数:operator typeName(); 请注意以下几点:转换函数必须是类方法; 转换函数不能指定返回类型;(因为typeName已经制定了转换函数要干嘛要转换为什么类型) 转换函数不能有参数。例如转换为 double类型的函数的原型如下:operator double();typeName(这里为 double)指出了要转换成的类型因此不需要指定返回类型。转换函数是类方法意味着:它需要通过类对象来调用从而告知函数要转换的值。因此函数不需要参数。//要添加将 stone_wt对象转换为int 类型和 double 类型的函数需要将下面的原型添加到类声明中: operator int(); operator double();总之C为类提供了下面的类型转换。 1.只有一个参数的类构造函数用于将类型与该参数相同的值转换为类类型。例如将int值赋给Stonewt 对象时接受 int 参数的 Stonewt类构造函数将自动被调用。然而在构造函数声明中使用explicit 可防止隐式转换而只允许显式转换。2.被称为转换函数的特殊类成员运算符函数用于将类对象转换为其他类型。转换函数是类成员没有返回类型、没有参数、名为operator typeName()其中typeName 是对象将被转换成的类型。将类对象赋给typeName 变量或将其强制转换为typeName 类型时该转换函数将自动被调用。