一. 除了可以通过构造方法实现自动类型转换,还可以通过运算符重载实现自动类型转换
#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;
}