簡體   English   中英

操作員超載:Ostream / Istream

[英]Operator Overloading: Ostream/Istream

我的C ++類的實驗室作業有點麻煩。

基本上,我正在嘗試獲取“ cout << w3 << endl;”。 正常工作,以便在我運行程序時控制台顯示“ 16”。 我已經知道我需要使用ostream重載操作,但是我不知道在哪里放置或如何使用它,因為我的教授從未談論過它。

不幸的是,我不得不使用格式“ cout << w3”而不是“ cout << w3.num”。 我知道,后者會更快,更容易,但這不是我的決定,因為作業需要我以前一種方式鍵入。

main.cpp中:

#include <iostream>
#include "weight.h"

using namespace std;
int main( ) {

    weight w1(6);
    weight w2(10);
    weight w3;

    w3=w1+w2;
    cout << w3 << endl;
}

weight.h:

#ifndef WEIGHT_H
#define WEIGHT_H

#include <iostream>

using namespace std;

class weight
{
public:
    int num;
    weight();
    weight(int);
    weight operator+(weight);

};

#endif WEIGHT_H

weight.cpp:

#include "weight.h"
#include <iostream>

weight::weight()
{

}

weight::weight(int x)
{
    num = x;
}

weight weight::operator+(weight obj)
{
    weight newWeight;
    newWeight.num = num + obj.num;
    return(newWeight);
}

TL; DR:如何通過重載ostream操作使main.cpp中的“ cout << w3”行工作?

提前致謝!

在班上結交朋友

friend ostream & operator << (ostream& ,const weight&);

將其定義為:

ostream & operator << (ostream& os,const weight& w)
{
  os<<w.num;
  return os;
}

這里

class weight
{
public:
    int num;
    friend std::ostream& operator<< (std::ostream& os, weight const& w)
    {
        return os << w.num;
    }
    // ...
};

或者,創建一個to_string方法,將weight.num轉換為string ;-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM