何谓转换构造函数,来举个简单例子:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class a
{
public:
int x, y;
a(int i, int j=2) :x(i), y(j)
{
}
};
int main()
{
a t1(4);
a t2 = 3;//转换构造函数
cout <<t1.x<<" "<<t1.y<< endl;
cout << t2.x << " " << t2.y << endl;
return 0;
}
就是将一般参数类型隐式转为类类型,如果要避免这种情况一般在构造函数前加上expilcit关键词。而且值得注意的是转换构造函数只接受一个参数,但是如上述所示,如果有提供默认参数的也可以。
上面展示了有基本参数类型转为类类型,那么将类类型转为一般类型如int double等是什么呢? 答案是转换函数,但是必须要注意以下几点:
1.它必须是类方法
2.不能指定返回类型
3.不接受参数
来看个简单示例:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class a
{
public:
int x, y;
a(int i, int j=2) :x(i), y(j)
{
}
operator int()
{
return this->x;
}
};
int main()
{
a t1(4);
int c = int(t1);
cout <<c<<endl;
return 0;
}
结果:
这就是简单的转换构造函数和转换函数的区别,感叹c++的博大精深和自己的孤陋寡闻。。。