操作员超载:Ostream/Istream [英] Operator Overloading: Ostream/Istream

查看:91
本文介绍了操作员超载:Ostream/Istream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在为C ++类进行实验分配时遇到了麻烦.

I'm having a bit of trouble with a lab assignment for my C++ class.

基本上,我正在尝试获取"cout<< w3<< endl;".正常工作,以便在我运行程序时控制台显示"16".我发现我需要使用ostream重载操作,但是我不知道在哪里放置或如何使用它,因为我的教授从未谈论过它.

Basically, I'm trying to get the "cout << w3 << endl;" to work, so that when I run the program the console says "16". I've figured out that I need to use an ostream overload operation but I have no idea where to put it or how to use it, because my professor never spoke about it.

不幸的是,我不得不使用格式"cout<< w3"而不是"cout<< w3.num".我知道,后者会更快,更容易,但这不是我的决定,因为作业需要我以前一种方式键入.

Unfortunately, I HAVE to use the format "cout << w3" and not "cout << w3.num". The latter would be so much quicker and easier, I know, but that's not my decision since the assignment necessitates I type it in the former way.

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:

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"行起作用?

TL;DR: how can I make the "cout << w3" line in main.cpp work by overloading the ostream operation?

提前谢谢!

推荐答案

在您的班级中添加好友功能

Make a friend function in your class

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

将其定义为:

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

请参见此处

这篇关于操作员超载:Ostream/Istream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆