首页 >> 民生娱乐

运算符重载转换运算符覆盖

民生娱乐  2021-08-24 13:33 字号: 大 中 小

为什么需要转换运算符?   我们大家知道对于内置类型的数据我们可以通过强制转换符的使用来转换数据,例如(int)2.1f;自定义类也是类型,那么自定义类的对象在很多情况下也需要支持此操作,C++提供了转换运算符重载函数,它使得自定义类对象的强转换成为可能。

转换运算符的生命方式比较特别,方法如下:

operator 类名();

转换运算符的重载函数是没有返回类型的,它和类的构造函数,析构函数一样是不遵循函数有返回类型的规定的,他们都没有返回值。

下面我看一个例子,看看它是如何工作的:

C++ 代码

#include iostream

using namespace std;

class Test

{

public:

Test(int a = 0)

{

coutthis\":\"\"载入构造函数!\"aendl;

Test::a = a;

}

Test(Test temp)

{

cout\"载入拷贝构造函数!\"endl;

Test::a = temp.a;

}

但由于没有得到直接证据 ~Test()

{

coutthis\":\"\"载入析构函数!\"this-aendl;

t();

}

operator int()//转换运算符

{

coutthis\":\"\"载入转换运算符函数!\"this-aendl;

return Test::a;

}

public:

int a;

};

int main()

{

Test b(99);

cout\"b的内存地址\"bendl;

cout(int)bendl;//强转换

system(\"pause\");

}

在例子中我们利用转换运算符将Test类的对象强转换成了int类型并输出,注意观察转换运算符函数的运行状态,发现并没有产生临时对象,证明了它与普通函数并不相同,虽然它带有return语句。

在很多情况下,类的强转换运算符还可以作为类对象加运算重载函数使用,尽管他们的意义并不相同,下面的例子,就是利用转换运算符,将两个类对象转换成int后,相加并创建临时类对象,后再赋给另一个对象。

代码如下

C++ 代码

#include iostream

using namespace std;

class Test

{

public:

Test(int a = 0)

{

coutthis\":\"\"载入构造函数!\"aendl;

Test::a = a;

}

Test(Test temp)

{

cout\"载入拷贝构造函数!\"endl;

Test::a = temp.a;

}

~Test()

{

coutthis\":\"\"载入析构函数!\"this-aendl;

t();

}

operator int()

{

coutthis\":\"\"载入转换运算符函数的内存地址:\"this-aendl;

return Test::a;

}

public:

int a;

};

int main()

{

Test a(100),b(100),c;

cout\"a的内存地址\"a\" b的内存地址\"bendl;

c=Test((int)a+(int)b);//显示式转换

cout\"c的内存地址\"cendl;

ndl;

system(\"pause\");

}

代码中的c=a+b;属于隐式转换,它的实现过程与c=Test((int)a+(int)b);完全相同。

成都哪白癜风医院好
贵州治疗白癜风哪家医院好
西安妇科诊疗医院
推荐资讯