通过运算符重载实现类型转换

一. 除了可以通过构造方法实现自动类型转换,还可以通过运算符重载实现自动类型转换

#include <iostream>

class three
{
	int i;
public:
	three(int I = 0, int = 0) : i(I){}
};

class four
{
	int x;
public:
	four(int X) : x(X){}
	operator three() const
	{
		return three(x);
	}
};

void g(three){}

int main()
{
	four Four(1);
	g(Four);
	g(1);

	return 1;
}

二. 如果不用自动转换,那么string类中要为需要的每一个C函数库的函数写一个包装函数,例如strcmp

#include <string>
#include <stdlib.h>

class string
{
	char* s;
public:
	string(const char* S = "")
	{
		s = (char*)malloc(strlen(S) + 1);
		strcpy(s, S);
	}
	~string()
	{
		free(s);
	}
	int Strcmp(const string& S) const
	{
		return ::strcmp(s, S.s);
	}
};


三. 通过使用自动转换,不需要为标准C函数库中的字符串函数写包装函数

#include <string>
#include <stdlib.h>

class string
{
	char* s;
public:
	string(const char* S = "")
	{
		s = (char*)malloc(strlen(S) + 1);
		strcpy(s, S);
	}
	~string()
	{
		free(s);
	}
	operator const char*() const
	{
		return s;
	}
};

int main()
{
	string s1("hello"), s2("three");
	strcmp(s1,s2); //standard c function
	strspn(s1, s2); //any string function

	return 1;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值