请教:C++重载输出操作符<<的问题, cout.operator()是什么东东?
问题来自我的一篇 学习博客 :
http://blog.csdn.net/sergery/article/details/8043203
问题1:cout.operator <<() 该怎么用?
#include <iostream>#include <string>using namespace std;void main(){ cout.operator <<("csdn"); // 0046E01,是个地址? 为什么不是输出字符串"csdn"?}
#include <iostream>#include <string>using namespace std;class Student{public: // 存 void setname(string s){ name = s;} void setage(int y){age = y; } void setaddress(string add){address = add;} // 取 string getname(){return name;} int getage(){return age;} string getaddress(){return address;} Student(string name="",int age=0,string address="") { this->name = name; this->age = age; this->address = address; } ~Student(){} //重载 运算符<< : 把 "operator<<" 看作是函数名, 返回类型是 ostream类型的对象引用 friend ostream& operator<< (ostream &os,Student &st) { os<<st.name<<"------"<<st.age<<"------"<<st.address<<endl; return os; }protected: private: string name; int age; string address;};void main(){ Student x1("刘莉莉",22,"东风路369号"); cout<<x1; //cout<<x1 ---结果OK,问题是这个写法很怪,是谁在调用那个重载函数?,x1显然是个参数,那是cout调用的 operator<< ? /* "<<" 是个什么东东? C++ Prime P6 这是个 "输出操作符", 其左边是ostream对象cout,右边是要输出的值 它的操作返回输出流本身cout,也就是可以连续写的原因. */ // 既然 cout是 ostream对象,那么可以用 . 的形式 访问ostream的成员函数 // 但是 operator<< 在本程序中已经重载了,要按照本程序的形参格式传入参数 ? ostream z; cout.operator<<(z,x1); // 编译通不过...}
#include <iostream>#include <iomanip>#include <sstream>int main(){ std::istringstream input(" \"Some text.\" "); volatile int n = 42; double f = 3.14; bool b = true;; std::cout << n // int overload << ' ' // non-member overload << std::boolalpha << b // bool overload << " " // non-member overload << std::fixed << f // double overload << input.rdbuf() // streambuf overload << &n // bool overload << std::endl; // function overload}