C++类与基础类型之间的隐式转换
一、前提条件:
1.类的构造函数只有一个参数;
2.类的构造函数有两个参数,但第二个参数必须有默认值,第一个可有可无;
#include<iostream>
using namespace std;
class Point {
int x, y;
public:
Point(int _x=0 , int _y=0) :x(_x), y(_y) {}//第二个参数必须为默认
friend ostream& operator<<(ostream& out, Point d)
{
out << "(" << d.x << "," << d.y << ")" ;
return out;
}
};
void fn(const Point &p) { //调用fn时候发生隐式转换
cout << p<<"\n";
}
int main() {
fn(3);
system("pause");
}
输出结果: