类类型是否能够转为普通类型?
类型转换函数
C++类中可以定义类型转换函数
类型转换函数用于将类对象转换为其他类型
#include <iostream>
#include <string>
using namespace std;
class Test
{
int mvalue;
public:
Test (int i = 0)
{
mvalue = i;
}
int value_a()
{
return mvalue;
}
operator int()
{
return mvalue;
}
};
int main()
{
Test t(100);
int i = t;
//int i = t.operator int();
cout << "t.value_a="<<t.value_a()<<endl;
cout << "i ="<<i<<endl;
return 0;
}
输出:
t.value_a=100
i =100
例:
#include <iostream>
#include <string>
using namespace std;
class Test;
class Value
{
public:
Value()
{
}
explicit Value(Test& t)
{}
};
class Test
{
int mvalue;
public:
Test (int i = 0)
{
mvalue = i;
}
int value_a()
{
return mvalue;
}
operator Value()
{
Value ret;
return ret;
}
};
int main()
{
Test t(100);
Value v = t;
// int i = t;
//Value v =t.operator Value();
//cout << "t.value_a="<<t.value_a()<<endl;
// cout << "i ="<<i<<endl;
return 0;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。