注册 登录
编程论坛 C++教室

求教编程题关于c++ 输出重载

borntimec 发布于 2012-07-01 18:24, 496 次点击
  1 #include <iostream>
  2 #include <cstring>
  3 using namespace std;
  4
  5 class Girl{
  6     string name;
  7     int age;
  8     bool hasLove;
  9 public:
 10     Girl()
 11     {
 12         cout << "Girl()" << endl;
 13     }
 14     Girl(string n, int a, bool h)
 15     {
 16         cout << "Girl(string, int, bool)" << endl;
 17         name = n;
 18         age = a;
 19         hasLove = h;
 20     }         
 21         
 22     friend ostream &operator<<(ostream&, Girl&);
 23                     
 24     void show() const  
 25     {                    
 26         cout << name << ":" << age << ":" << (hasLove?"has":"not") << endl;
 27     }                           
 28                                 
 29 /*                                    
 30     friend ostream &operator<<(ostream &o, const Girl &g)
 31     {
 32         g.show();
 33         return o;
 34     }
 35 */
 36 };
 37        
 38 ostream &operator<<(ostream &o, Girl &g)
 39 {
 40     o << Girl.name << Girl.age << Girl.hasLove;
 41     return o;
 42 }
 43
 44 int main()
 45 {
 46     Girl g("han", 22, false);
 47     cout << g << endl;
 48     g.show();
 49     Girl g2;
 50     g2.show();
 51
 52     return 0;
 53 }
 54



gcc报错

construct.cpp: In function ‘std::ostream& operator<<(std::ostream&, Girl&)’:
construct.cpp:40:11: error: expected primary-expression before ‘.’ token
construct.cpp:40:24: error: expected primary-expression before ‘.’ token
construct.cpp:40:36: error: expected primary-expression before ‘.’ token
5 回复
#2
一只小蚂蚁2012-07-01 18:36
运算符重载的话 要定义和实现分别放进。h和。cpp 不然用friend会报错
#3
borntimec2012-07-01 20:02
回复 2楼 一只小蚂蚁
谢谢,但为什么要分开
#4
一只小蚂蚁2012-07-01 21:39
。。编译不过去  而且写程序要标准 实现和定义放一起容易出问题的
你试试定义static放在。h文件 有时也会出现问题
#5
rjsp2012-07-02 08:21
你代码是抄的吧
38 ostream &operator<<(ostream &o, Girl &g)
39 {
40     o << Girl.name << Girl.age << Girl.hasLove;
41     return o;
42 }
应该是
     friend ostream& operator<<(ostream& o, const Girl& g)
     {
         o << g.name << g.age << g.hasLove;
         return o;
     }

#6
一只小蚂蚁2012-07-03 14:18
如果friend只声明 没实现  需要分开写要声明友元函数的声明与实现
楼上的有实现是没问题的
1