类型学转换成其他类型有两种方式:
创新互联专业为企业提供江宁网站建设、江宁做网站、江宁网站设计、江宁网站制作等企业网站建设、网页设计与制作、江宁企业网站模板建站服务,10余年江宁做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
一、用构造函数,将基本类型转为构造类型
1.用初始化的形式;
class X
{
public:
X(int n);
~X();
};
void f(X arg);
...
int main(){
X(3);
X=a;//a隐式调用构造函数X(int n);
f(5);//把5调用构造函数X(int n)转为X arg.然后调用构造函数。
return 0;
}
二、因为带参数的构造函数无法将类类型转为基本类型,所以设置类型转换函数
#include
using namespace std;
class rational
{
public:
rational();
rational(int n,int d=1);
rational(double x);//将double类型转换成类类型。
operator double();//将类类型转变为double类型,且注意其没有返回值。
friend rational& operator+(const rational&, const rational&);
friend ostream & operator <<( ostream& os, const rational&);
//注意这里输出类ostream前面不可以加const因为在输出流经过os时会修改os
//且类型一定是引用类型因为必须用cout对象本身
~rational();
private:
int numerator;
int denominator;
};
int gcd(int a, int b);
rational::rational()
{
numerator = 0;
denominator = 0;
}
rational::rational(int n,int d){
int g;
if (d == 1){
numerator = n;
denominator = d;
}
else{
g = gcd(n, d);//求分子分母的最大公约数
numerator = n / g;//把分母化成最简;
denominator = d / g;
}
}
rational::rational(double x){
int a, b, g;
a = int(x*1e5);//x乘10的5次方。把小数变成整数
b = int(1e5);
g = gcd(a, b);
numerator = a / g;
denominator = b / g;
}
rational::~rational()
{
}
rational::operator double(){//虽然没有返回值依然要返回double类型的数。
return double(numerator) / double(denominator);
}
rational& operator +(const rational& a, const rational& b){
rational c;
int d = a.denominator*b.denominator;
int n = a.numerator*b.denominator + a.denominator*b.numerator;
int g = gcd(n, d);
c.denominator = d / g;//将分子分母化为最简
c.numerator = n / g;
return c;//返回类型是引用还是类类型都可以。
}
ostream& operator <<(ostream& os, const rational& a){
os << a.numerator;
if (a.denominator != 1){
os << "/" << a.denominator;
}
return os;//这里返回os类型的引用目的是连续使用cout<<"ss"<<"sss";
}
int gcd(int n, int d){//求最大公约数的算法
if (d == 0) return n;
else{
return gcd(d, n%d);
}
}
int main(){
rational a(2, 4);
rational b = 0.3;
rational c = a + b;
cout << double(a) << "+" << double(b)<<"="< //将类类型对象a,b,c转换成double类型。 cout << a << "+" << b << "=" << c << endl; double x = b; c = x + 1 + 0.6; cout << x << "+" << 1 << "+" << 0.6 << "=" << c << endl; cout << rational(x) << "+" << rational(1) << "+" << rational(0.6) << "=" << c << endl; system("pause"); }
网站标题:类类型与其他类型的转换
分享链接:http://cdweb.net/article/jojgic.html