C++学习 (使用类)
2015-11-19 18:22
211 查看
友元函数,
常用的是对<<的重载
这时候使用 cout<
然后就是今天发现了要给比较神奇的事情。。。原来学的C,c++真的是渣渣,原来结构体也可以类型转换的,只有定义了相应构造函数,而且还分强制类型转换,和隐式转换
如果不想让它这样 加上 explicit
这样就关闭了隐式,但是显示转换还是可以得
常用的是对<<的重载
#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; }
这样就关闭了隐式,但是显示转换还是可以得
相关文章推荐
- c语言文件IO库函数——APUE学习笔记(1)
- 魔方矩阵 C++实现
- C++ 二叉树的遍历
- C语言错误日志——指针返回值与数组
- C语言公式--爱情的年轮
- C++ListControl颜色控制
- C语言编程中借助pthreads库进行多线程编程的示例
- c++ txt文件的读写及乱码问题解决
- 用C语言进行最基本的socket编程
- C++中string erase函数的使用(转载)
- effective c++ 尽量少做转型动作(2)
- vc++ mfc中拖动效果的实现 借助于CImageList
- 【转】C语言产生随机数
- C++中for循环的5种语法,你可知道?
- c++的动态申请内存
- C++语言中的 静态类型员 用法
- LeetCode String to Integer (atoi) c++
- C++冒泡排序
- 一个优秀windows C++ 程序员该有哪些知识
- C++ Primer Plus第六版 第十二章 编程练习答案