pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

'朋友'功能和<<運算符重載:為類

#39;friend#39; functions and lt;lt; operator overloading: What is the proper way to overload an operator for a class?(朋友功能和lt;lt;運算符重載:為類重載運算符的正確方法是什么?) - IT屋-程序員軟件開發技術分享
本文介紹了'朋友'功能和<<運算符重載:為類重載運算符的正確方法是什么?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

在我正在處理的一個項目中,我有一個 Score 類,在下面的 score.h 中定義.我試圖重載它,所以當對它執行 << 操作時,會打印 _points + " " + _name .

In a project I'm working on, I have a Score class, defined below in score.h. I am trying to overload it so, when a << operation is performed on it, _points + " " + _name is printed.

這是我嘗試做的:

ostream & Score::operator<< (ostream & os, Score right)
{
    os << right.getPoints() << " " << right.scoreGetName();
    return os;
}

以下是返回的錯誤:

score.h(30) : error C2804: binary 'operator <<' has too many parameters

(這個錯誤實際上出現了4次)

(This error appears 4 times, actually)

我設法通過將重載聲明為友元函數來使其工作:

I managed to get it working by declaring the overload as a friend function:

friend ostream & operator<< (ostream & os, Score right);

并從 score.cpp 中的函數聲明中刪除 Score::(實際上并未將其聲明為成員).

And removing the Score:: from the function declaration in score.cpp (effectively not declaring it as a member).

為什么這行得通,而前一段代碼卻行不通?

Why does this work, yet the former piece of code doesn't?

感謝您的時間!

編輯

我刪除了頭文件中所有對重載的提及...但我收到以下(也是唯一的)錯誤.二進制'<<': 沒有找到使用Score"類型的右側操作數的運算符(或者沒有可接受的轉換)為什么我的測試在 main() 中找不到合適的重載?(這不是包含,我檢查過)

I deleted all mentions to the overload on the header file... yet I get the following (and only) error. binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion) How come my test, in main(), can't find the appropriate overload? (it's not the includes, I checked)

以下是完整的分數.h

#ifndef SCORE_H_
#define SCORE_H_

#include <string>
#include <iostream>
#include <iostream>

using std::string;
using std::ostream;

class Score
{

public:
    Score(string name);
    Score();
    virtual ~Score();
    void addPoints(int n);
    string scoreGetName() const;
    int getPoints() const;
    void scoreSetName(string name);
    bool operator>(const Score right) const;

private:
    string _name;
    int _points;

};
#endif

推薦答案

注意:您可能想查看 運算符重載常見問題解答.

二元運算符可以是其左側參數類的成員,也可以是自由函數.(某些運算符,如賦值,必須是成員.)由于流運算符的左側參數是一個流,因此流運算符要么必須是流類的成員,要么是自由函數.為任何類型實現 operator<< 的規范方法是:

Binary operators can either be members of their left-hand argument's class or free functions. (Some operators, like assignment, must be members.) Since the stream operators' left-hand argument is a stream, stream operators either have to be members of the stream class or free functions. The canonical way to implement operator<< for any type is this:

std::ostream& operator<<(std::ostream& os, const T& obj)
{
   // stream obj's data into os
   return os;
}

注意它不是一個成員函數.另請注意,它需要對象按 const 引用進行流式處理.那是因為您不想復制對象以流式傳輸它,并且您也不希望流式傳輸更改它.

Note that it is not a member function. Also note that it takes the object to stream per const reference. That's because you don't want to copy the object in order to stream it and you don't want the streaming to alter it either.

有時您希望流式傳輸內部無法通過其類的公共接口訪問的對象,因此操作員無法獲取它們.那么你有兩個選擇:要么將一個公共成員放入進行流式傳輸的類中

Sometimes you want to stream objects whose internals are not accessible through their class' public interface, so the operator can't get at them. Then you have two choices: Either put a public member into the class which does the streaming

class T {
  public:
    void stream_to(std::ostream&) const {os << obj.data_;}
  private:
    int data_;
};

并從操作員那里調用:

inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
   obj.stream_to(os);
   return os;
}

或者讓操作員成為朋友

class T {
  public:
    friend std::ostream& operator<<(std::ostream&, const T&);
  private:
    int data_;
};

以便它可以訪問類的私有部分:

so that it can access the class' private parts:

inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
   os << obj.data_;
   return os;
}

這篇關于'朋友'功能和&lt;&lt;運算符重載:為類重載運算符的正確方法是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How can I read and manipulate CSV file data in C++?(如何在 C++ 中讀取和操作 CSV 文件數據?)
In C++ why can#39;t I write a for() loop like this: for( int i = 1, double i2 = 0; (在 C++ 中,為什么我不能像這樣編寫 for() 循環: for( int i = 1, double i2 = 0;)
How does OpenMP handle nested loops?(OpenMP 如何處理嵌套循環?)
Reusing thread in loop c++(在循環 C++ 中重用線程)
Precise thread sleep needed. Max 1ms error(需要精確的線程睡眠.最大 1ms 誤差)
Is there ever a need for a quot;do {...} while ( )quot; loop?(是否需要“do {...} while ()?環形?)
主站蜘蛛池模板: 发光字|标识设计|标牌制作|精神堡垒 - 江苏苏通广告有限公司 | 壹作文_中小学生优秀满分作文大全 | H型钢切割机,相贯线切割机,数控钻床,数控平面钻,钢结构设备,槽钢切割机,角钢切割机,翻转机,拼焊矫一体机 | 合肥仿石砖_合肥pc砖厂家_合肥PC仿石砖_安徽旭坤建材有限公司 | 手术室净化厂家-成都做医院净化工程的公司-四川华锐-15年特殊科室建设经验 | YAGEO国巨电容|贴片电阻|电容价格|三星代理商-深圳市巨优电子有限公司 | 上海橡胶接头_弹簧减震器_金属软接头厂家-上海淞江集团 | 顶呱呱交易平台-行业领先的公司资产交易服务平台 | 磁力轮,磁力联轴器,磁齿轮,钕铁硼磁铁-北京磁运达厂家 | 安徽集装箱厂-合肥国彩钢结构板房工程有限公司| 称重传感器,测力传感器,拉压力传感器,压力变送器,扭矩传感器,南京凯基特电气有限公司 | POS机办理_个人pos机免费领取-银联pos机申请首页 | 广州中央空调回收,二手中央空调回收,旧空调回收,制冷设备回收,冷气机组回收公司-广州益夫制冷设备回收公司 | 洗砂机械-球磨制砂机-洗沙制砂机械设备_青州冠诚重工机械有限公司 | 广西绿桂涂料--承接隔热涂料、隔音涂料、真石漆、多彩仿石漆等涂料工程双包施工 | 电销卡_稳定企业大语音卡-归属地可选-世纪通信 | 胀套-锁紧盘-风电锁紧盘-蛇形联轴器「厂家」-瑞安市宝德隆机械配件有限公司 | 无线对讲-无线对讲系统解决方案-重庆畅博通信 | 上海办公室装修,办公楼装修设计,办公空间设计,企业展厅设计_写艺装饰公司 | 高空重型升降平台_高空液压举升平台_高空作业平台_移动式升降机-河南华鹰机械设备有限公司 | 山东齐鲁漆业有限公司【官网】-工业漆专业生产厂家 | 全自动实验室洗瓶机,移液管|培养皿|进样瓶清洗机,清洗剂-广州摩特伟希尔机械设备有限责任公司 | 优考试_免费在线考试系统_培训考试系统_题库系统_组卷答题系统_匡优考试 | 青岛侦探_青岛侦探事务所_青岛劝退小三_青岛婚外情取证-青岛王军侦探事务所 | 众能联合-提供高空车_升降机_吊车_挖机等一站工程设备租赁 | 减速机三参数组合探头|TSM803|壁挂式氧化锆分析仪探头-安徽鹏宸电气有限公司 | 全自动五线打端沾锡机,全自动裁线剥皮双头沾锡机,全自动尼龙扎带机-东莞市海文能机械设备有限公司 | 扬尘在线监测系统_工地噪声扬尘检测仪_扬尘监测系统_贝塔射线扬尘监测设备「风途物联网科技」 | 400电话_400电话申请_888元包年_400电话办理服务中心_400VIP网 | 不锈钢螺丝 - 六角螺丝厂家 - 不锈钢紧固件 - 万千紧固件--紧固件一站式采购 | 撕碎机,撕破机,双轴破碎机-大件垃圾破碎机厂家 | 合同书格式和范文_合同书样本模板_电子版合同,找范文吧 | 化妆品加工厂-化妆品加工-化妆品代加工-面膜加工-广东欧泉生化科技有限公司 | 智慧物联网行业一站式解决方案提供商-北京东成基业 | 福州甲醛检测-福建室内空气检测_环境检测_水质检测-福建中凯检测技术有限公司 | 棕刚玉_白刚玉_铝酸钙-锐石新材料 | 钢骨架轻型板_膨石轻型板_钢骨架轻型板价格_恒道新材料 | 月嫂_保姆_育婴_催乳_母婴护理_产后康复_养老护理-吉祥到家家政 硫酸亚铁-聚合硫酸铁-除氟除磷剂-复合碳源-污水处理药剂厂家—长隆科技 | 消泡剂-水处理消泡剂-涂料消泡剂-切削液消泡剂价格-东莞德丰消泡剂厂家 | 粘度计NDJ-5S,粘度计NDJ-8S,越平水分测定仪-上海右一仪器有限公司 | 浙江富广阀门有限公司|