您的位置:首页 > 编程语言 > C语言/C++

C++学习 (使用类)

2015-11-19 18:22 211 查看
友元函数,

常用的是对<<的重载

#include <stdio.h>
#include <iostream>

using namespace std;
struct node
{
double x;
double y;
node(){};
node(int _x, int _y){
x =(double) _x;
y = (double) _y;
}
node (double _x, double _y)
{
x =_x;
y = _y;
}

friend void operator <<(ostream & os, const node &t);

};
void operator <<(ostream & os, const node &t){
os << "x : "<<t.x << "  y :"<< t.y<<endl;
}

int main()
{
node a = node(1.0, 2.0);
node b = node(3.0, 4.0);
cout<<a;
//cout<<a<<b<<endl; error!!!!
}


这时候使用 cout<

std::ostream & operator<<(std::ostream & os, const node &t){

os << "x : "<<t.x << "  y :"<< t.y<<endl;
return os;
}
并且一定是 std::ostream &


然后就是今天发现了要给比较神奇的事情。。。原来学的C,c++真的是渣渣,原来结构体也可以类型转换的,只有定义了相应构造函数,而且还分强制类型转换,和隐式转换

#include <stdio.h>
#include <iostream>

using namespace std;
struct node
{
double x;
double y;
node(){};
node(int _x){
x =(double) _x;
}
node (double _x)
{
x =_x;
}
};
int main()
{
node now;
now = double(1.3);
cout<<now.x<<endl;//隐式
}


如果不想让它这样 加上 explicit

#include <stdio.h>
#include <iostream>

using namespace std;
struct node
{
double x;
double y;
node(){};
explicit node(int _x){
x =(double) _x;
}
explicit node (double _x)
{
x =_x;
}
};
int main()
{
node now;
node = (double)1.3
// now = node(1.3); right
cout<<now.x<<endl;
}


这样就关闭了隐式,但是显示转换还是可以得
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: