基础知识要牢固。。。
================================================
类的自动类型转换和强制类型转换,有需要的朋友可以参考下。
1.可以将类定义成与基本类型或者另一个类相关,使得从一个类转换成另外一个类型是有意义的。
2.将基本类型转换成类(下面以double转换成Money类来举例):
假设定义了如下类:
class Money { private: double RMB; double DOLLAR; public: Money(); Money(double r, double d); Money(double r); ~Money(); friend ostream & operator<<(ostream & os, Money & m); };则其中的构造函数
Money(double r);可以讲double类型转换成Money类这个类型。
●只有接受一个参数的构造函数才能作为转换函数
●或者有多个参数,但是除第一个参数没有默认值外,其他所有的参数都有默认值,这样的构造函数也可作为转换函数
●在正常情况下,以下代码是有效的:
Money m; m = 12.3;这种转换成为隐式转换。
●隐式转换有时候会导致意外的类型转换,所以我们有时需要关闭隐式转换,这时我们使用关键字explicit:
explicit Money(double r);使用了关键字explicit后,则代码:
Money m; m = 12.3;是无效的,只能使用如下方式将double类型转换成Money类:
Money m(12.3);//或者类似初始化方式
3.类转换为其他类型:
●构造函数只能用于从某种类型到类类型的转换。要进行相反的转换,必须使用特殊的c++运算符函数---转换函数
●注意一下几点:
①转换函数必须是类的方法
②转换函数不能指定返回类型
③转换函数不能有参数
●转换函数举例:
假设有如下类定义:
class Money { private: double RMB; double DOLLAR; public: Money(); Money(double r, double d); Money(double r); ~Money(); operator double(); //转换函数,用于将Money类转换成double类型 friend ostream & operator<<(ostream & os, Money & m); };其中的
operator double(); //转换函数,用于将Money类转换成double类型就是我们定义的转换函数,定义方法是operator typeName()
转换函数的使用:
int main() { Money m(2.3); double result; result = m; cout << m; cout << result; return 0; }这样就可以将类转换成double。上例中也可以在result前加上(int)转换成整数类型。
======================================
#include <iostream>
#include <string>
using namespace std;
class A
{
int n;
public:
// 在此处补充你的代码
A(int n_):n(n_) {}
A() {}
A & operator ++()
{
n++;
return *this;
}
int operator ++ (int)
{
int tem;
tem = n;
n++;
return tem;
}
void operator = ( int n_)
{
n = n_;
}
operator int()
{
return n;
}
friend ostream & operator << (ostream &os,A a)
{
os<<a.n;
return os;
}
};
class B
{
private:
static int k;
static int Square(int n)
{
cout << "k=" << k <<endl;
return n * n;
}
friend int main();
};
int B::k;
int main()
{
A a1(1),a2(2);
cout << a1++ << endl;
(++a1) = 100;
//a1 = 100;
cout << a1 << endl;
cout << ++ a1 << endl;
cout << a1 << endl;
int n;
cin >> n;
while( n --)
{
cin >> B::k;
A a3(B::k);
cout << B::Square(a3) << endl;
}
return 0;
}