如何将一个类赋值给一个int,double等型的变量,可以采用重载类型的方法解决,如下:
1.没有重载int类型之前:
#include <iostream>
using namespace std;
class Test
{
public:
Test(int d = 0):data(d)
{
}
~Test()
{
}
public:
void Showdata()const
{
cout<<data<<endl;
}
private:
int data;
};
int main()
{
Test t(10);
t.Showdata();
int val1 = 100;
t = val1;
t.Showdata();
Test t1(200);
int val2 = 0;
val2 = t1;
cout<<val2<<endl;
return 0;
}
测试结果:
[root@localhost Test4_20]# g++ tt.cpp -o tt
tt.cpp: In function ‘int main()’:
tt.cpp:34:7: error: cannot convert ‘Test’ to ‘int’ in assignment
val2 = t1;
^
[root@localhost Test4_20]#
2.重载了int类型之后:
#include <iostream>
using namespace std;
class Test
{
public:
Test(int d = 0):data(d)
{
}
~Test()
{
}
public:
void Showdata()const
{
cout<<data<<endl;
}
public:
operator int()const
{
return data;
}
private:
int data;
};
int main()
{
Test t(10);
t.Showdata();
int val1 = 100;
t = val1;
t.Showdata();
Test t1(200);
int val2 = 0;
val2 = t1;
cout<<val2<<endl;
return 0;
}
输出结果:
[root@localhost Test4_20]# g++ tt.cpp -o tt
[root@localhost Test4_20]# ./tt
10
100
200
[root@localhost Test4_20]#