Constructor with ostream and istream parameters [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
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.

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);
...
}

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. */ }

Related

How to access a private variable which is within a function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
#include <iostream>
using namespace std;
class Test{
public:
int kk(int b){
return a=b+5;
}
private:
int a;
/*void priv()
{
int a; // How to access a , if this part was not commented
}*/
};
int main()
{
Test kris;
cout<< kris.kk(5)<<endl;
return 0;
}
I was trying to understand the concept of private and public members and the methods to access the private members when they are defined in a class. I wanted to rephrase the question to how to access a variable, which is local to a private function via an object of class "Test" (as defined in the code).
I found the answer to it and experimented it with my own code and i was able to execute the code. Below is the code
#include <iostream>
using namespace std;
class Test{
public:
int xyz_1(){
return xyz_2() ;
}
private:
int xyz_2(){
int a=5;
return a;
}
};
int main()
{
Test kris;
cout<< kris.xyz_1()<<endl<<"Sorry for the confusion"<<endl;
return 0;
}
How to access a private variable which is within a function
You're trying to access a local variable of priv() in the function kk() which is impossible unless the visibility of the variable a is either public or outside the function (in case with classes) under private: (which will make it accessible to all member functions). In a rough way, you're trying to do something:
void fun1() {
int a;
}
void fun2() {
std::cout << a;
}
Which is not possible.
You might need to think more about your design and what you achieve.
Do you want to have a private member in the class to access the function? Then declare your variable "a" as a private member in your class, and use this.a inside your function. If you want a child class to be also able to access your private member, make the variable protected instead of private.
If you want to restrict any other function in your class from accessing that member, then I would be curious about what your intention is. If you try to hide the implementation you might want to look into the Pimpl technique. However, it also has a very specific use case (besides that you can use it to hide the implementation from developers, too).
https://en.cppreference.com/w/cpp/language/pimpl[pimpl programming technique]1
If you add more information about your problem and intention I'm sure people can give you better directions.

How to use overloading operator without the include friend? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
for unit testing:
ostream& operator << (ostream&os,const Unit&C)
{
os << C.GetUnitName() << C.GetUnitID() << C.GetCredits();
return os;
}
istream& operator >> (istream&input,Unit&C)
{
string UnitName,UnitsID;
int Crediet;
input >> UnitName >> UnitsID>> Crediet;
C.setUnitName(UnitName);
C.setUnitID(UnitsID);
C.setCredits(Crediet);
return input;
}
text input file: Database ICT222 3
why I get the outfile:"0x6afd64"?
How to use overloading operator without the include friend?
You can always overload without friend provided you only use public members of your class in the operator...
If you need internals, bad luck, then you need a friend declaration. You might compile it in conditionally, though, for your testing builds only:
class C
{
#ifdef SOME_MACRO_IDENTIFYING_UT_BUILD
friend auto operator<<(/* ... */) { /* ... */ }
#endif
};
You won't be able to prevent the user having the macro defined, too, though. Variant:
class C
{
#ifdef SOME_MACRO_IDENTIFYING_UT_BUILD
friend
#endif
auto operator<<(/*...*/); // no implementation in header
};
(or just skip the ifdef/endif entirely, would not matter much...)
In the CPP file then (which would already be compiled, so user cannot influence unless having sources; not applicable for templates, though):
#ifdef SOME_MACRO_IDENTIFYING_UT_BUILD
auto operator<<(/* ... */)
{
// implementation showing your internals
}
#else
auto operator<<(/* ... */)
{
// some implementation you consider safe for general use...
//
// if you don't want the user to use it at all, you
// even might throw an exception - I don't consider
// it the best idea, but at least...
}
#endif
All you yet need to do is having your specific test build run with the macro defined, GCC/clang: -D option, MSVC /D.

How can I (cleanly!) subclass std::stringstream for a customization? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a logging class with a std::stringstream member. I use it's output << overloading to get a nice easy means for catching all the data types std::stringstream gives me for free.
Here's the problem. After sending data into the stream, I want an easy way to flush it automatically to my destination (which is variable/dynamic in nature).
std::ostream will "auto flush" if you send an endl down it. That's and acceptable solution I would duplicate.
How can I implement that myself? Note that I don't want to override every operator<<() overload in std::stringstream!
I've done a similar thing. What I do is use an unnamed class instance to consume the output and put the flushing in the destructor. Something like this:
int i = 0;
MyClass() << "This is a log message containing an int: " << i;
// here, the class destructs and does whatever you need to do to flush the stream
Instead of subclassing std::stringstream, it's prefered to use composition (see Composition over inheritance).
With this, your class would look like this:
class Log{
std::stringstream _stream;
[...] // Constructor and other class logic
public:
Log& operator<<(string s){
_stream << s << endl;
return *this;
}
};

C++ eclipse. Abstract class won't compile [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I got a problem regarding Eclipse when creating abstract classes. I'm not very used to dealing with header files and such, my code basically looks as follows: (not displaying everything, just the basic class to give an idea of how it looks)
Equipment.h
namespace Equipments {
class Equipment{
public:
virtual ~Equipment();
virtual std::string get_category() const = 0;
protected:
Equipment(std::string name);
private:
const std::string name_;
};
class Weapon : public Equipment {
public:
Weapon(std::string name, std::string something_else);
virtual ~Weapon();
std::string get_category() const override { return "Weapon"; };
private:
const std::string something_else_;
};
} //end of namespace
Now, I got a problem with both the .h and .cpp file
in the .h file, under the weapon constructor, I'm used to writing (since I don't use header files):
Weapon(std::string name, std::string something_else)
: Equipment{name}, something_else_{something_else}
{}
Since I can't do this really (to my knowledge), how do I send parameters to my parent class? (in this case, letting eclipse know that I want my name parameter sent to Equipment parent class)
Should I do it in the .cpp file and if so, how?
And now the second problem.
In the .cpp file I create my equipment class like this:
namespace Equipments {
Equipment::Equipment(std::string name) {
name_ = name;
}
Equipment::~Equipment() {
}
std::string Equipment::get_name()
{
return name_;
}
//etc
But I can't seem to create my Weapon class. If I try:
Equipment::Weapon(std::string name, std::string something_else)
I just get member decleration not found, and if I try:
Weapon::Weapon(std::string name, std::string something_else)
I get no matching function for call to 'Equipments::Equipment::Equipment()'
I'm just stuck with not knowing how eclipse want me to write my code, I know it's a bit of a noob problem but I haven't been using either header files or c++ in eclipse for quite a long time. I'm really close to just pick my laptop and program in ubuntu and gedit instead so I don't have to deal with the header classes, however, then I won't learn anything either.
But I can't seem to create my Weapon class. If I try:
Equipment::Weapon(std::string name, std::string something_else)
I just get member declaration not found,
Well, yes: your Weapon class is called Weapon, and it's constructor is called Weapon::Weapon. It inherits from Equipment, it isn't stored inside it.
and if I try:
Weapon::Weapon(std::string name, std::string something_else)
I get
no matching function for call to 'Equipments::Equipment::Equipment()'
That just means you left out the base class constructor (so it's trying to use the default constructor, which doesn't exist) - you don't show the whole code, but it ought to be
Weapon::Weapon(std::string name, std::string something_else)
: Equipment(name)
, something_else_(something_else)
{
}

What is this header error caused by? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm using the header file "sales.item"
I'm writing a little program and it is telling me that the header file, not my program, has an error. Somehow that last line isn't right. The error is saying that the string isbn is private.
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item item1, item2;
std::cin >> item1 >> item2;
if (item1.isbn() == item2.isbn()) { // this checks if item1 and item2 are same book
In the Sales_item class you forgot to make the isbn method public, and left it at its default private visibility.
It should, in short, read something like this:
class Sales_item
{
public:
return_value isbn();
}
Without the public: line it will be private by default in C++ classes.
I'm going to go out on a limb and guess that your class is defined something like this:
class Sales_item
{
std::string isbn;
}
Classes and structs have public, private, and protected labels for their member data, and classes have their members labelled as private by default. You should change it to read:
class Sales_item
{
public:
std::string isbn;
}
EDIT:
When you add () (with or without parameters) to an identifier, you are telling the compiler to call it like a function. Take out the ()'s and your code should work.