-3

I've got a question implementing a class constructor that has istream and ostream parameters. These values are to be used within the scope of the class. I am building a game that will ask questions and I want to use the istream parameter to collect the user input and the ostream to show things in the console.

class MyClass{

public:
    MyClass();
    MyClass(ostream& show, istream& userInput);
    ~MyClass();

    void anotherFunction(string name, string lastName);
    void executeProgram();

Can anyone explain a solution, and provide sample code, to make the scope of istream within the class accessible? How would I call this in the main class?

Edit: Hi and thank you for trying even i dont have clear output on this one.

What i am really looking for is to use this constructor as user interface of my program. This is a text based game which will accept 3 chars as options. I wanted to use this constructor to gather input. I hope that makes sense.

Drakn
  • 3
  • 2
  • What have you done so far? What is the problem that you are experiencing? – Dmitry Kuzminov Sep 06 '20 at 05:18
  • What you are describing does not make much sense. When you `#include ` you have all of the functions/operators available globally by default. You generally only pass `istream` and `ostream` references as parameter when you are creating `friend` functions to overload `<<` and `>>` for example. What are you hoping to accomplish? – David C. Rankin Sep 06 '20 at 05:18
  • It's irrelevant that they are streams. You just need to re-read your tutorial concerning the use of references. – Ulrich Eckhardt Sep 06 '20 at 09:15

2 Answers2

1

I don't see any particular problems here (and your question hasn't mentioned any). For example

#include <iostream>
#include <fstream>
using namespace std;

class MyClass
{
public:
    MyClass() : _in(cin), _out(cout) {}
    MyClass(istream& in, ostream& out) : _in(in), _out(out) {}
private:
    istream& _in;
    ostream& _out;
};

int main()
{
    ifstream in("in.txt");
    ofstream out("out.txt");
    MyClass mc(in, out);
    ...
}
john
  • 85,011
  • 4
  • 57
  • 81
0

The idiomatic C++ way is to not take the two stream parameters in constructor but define insertion and extraction operators for your class.

Goes like this:

class MyClass
{
public:
      /* define various accessors here */
};

ostream& operator<<(ostream& os, const MyClass& instance) { /* write out your class's representation here. */ }

istream& operator>>(istream& is, MyClass& instance) { /* set state in instance reading it from is. */ }
Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32