How to use overloading operator without the include friend? [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 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.

Related

Constructor with ostream and istream parameters [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
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. */ }

c++ use class or not for permutation algorithm [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have written a program, which takes an input vector of integers and prints all possible permutations of these integers.
In order to do that my program has two methods:
void Permutate(//input) and void DoPermute(//necessary arguments)
Only the method Permutate should be called by the user/client. DoPermutate is a recursive method which is firstly called by Permutate and provides the logic for the algorithm.
The question now: would you put Permutate and DoPermutate in a class and make DoPermutate private, or would you put both methods in the global scope and not use classes at all and thus expose DoPermutate to the user/client? I am asking this because cmath also has the utility methods in a global scope.
What would be a more elegant approach?
The question now: would you put Permutate and DoPermutate in a class
This is what I would to:
Declare Permutate in a namespace, such as:
namespace MyApp
{
// Declare
void Permutate( ... ); // Add all the necessary arguments,
// which can be input arguments ad
// output arguments.
}
Please note that the declaration does not expose whether a class is used in the implementation. That is detail of the implementation that does not need to be exposed in the interface.
If it is helpful to use a class in the implementation, use it.
namespace MyApp
{
// Helper class
struct PermutateClass { ... };
// Implement the user facing function.
void Permutate ( ... )
{
// Delegate the implementation to the helper class.
PermuateClass p(...);
p.doIt();
}
}
If it is not helpful to use a class, just use helper functions as needed.
namespace MyApp
{
// Helper function
void DoPermutate ( ... ) { ... }
// Implement the user facing function.
void Permutate ( ... )
{
// Delegate the implementation to the helper function.
DoPermutate p(...);
}
}
The key point I want to emphasize is that whether you use a helper class with a bunch of member functions or a bunch of non-member function is an implementation detail that you should be able choose without impacting the users of the user facing function.

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++ access violation when writing to typdef struct [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 6 years ago.
Improve this question
I have a struct defined in a header file. Then I have a singleton class where I am trying to use the struct. When I call ResetVars() from another class I get an access violation when it hits the line that says test.numResponses = "TEST". I am assuming this has something to do with initialization but I haven't been able to solve it. I am new to c++ and I have no idea how to get around this. Thanks for any help.
struct.h
typedef struct POLL_DATA
{
std::string numResponses;
std::string type;
std::string question;
} POLL_DATA;
ControlPolls.h
class ControlPolls
{
private:
static bool instanceFlag;
static ControlExitPolls *controlSingle;
ControlExitPolls();
POLL_DATA test;
public:
static ControlExitPolls* getInstance();
void ResetVars();
};
ControlPolls.cpp
#include "ControlPolls.h"
bool ControlPolls::instanceFlag = false;
ControlPolls* ControlPolls::controlSingle = NULL;
//Private Constructor
ControlExitPolls::ControlExitPolls()
{
};
//Get instance
ControlPolls* ControlPolls::getInstance()
{
if(!instanceFlag)
{
controlSingle = &ControlPolls();
instanceFlag = true;
return controlSingle;
}
else
{
return controlSingle;
}
}
void ControlExitPolls::ResetVars()
{
test.numResponses = "TEST";
}
callingClass.cpp
ControlPolls *controlSingleton;
controlSingleton = ControlPolls::getInstance();
controlSingleton->getInstance()->ResetVars();
You've been struck by C++'s Most Vexing Parse, a compiler rule that says anything that could be a function declaration is a function declaration. The culprit is this line:
POLL_DATA testPoll();
testPoll is treated as the declaration of a function with return type POLL_DATA. Try removing the brackets, or writing simply POLL_DATA testPoll; which implicitly calls the compiler-generated default constructor.
Another larger problem is that testPoll is a member of A, but you've hidden it and declared a local variable in your constructor, A::A(). I suggest you remove the constructor altogether because the implicit constructor will suffice.
Some more notes on your code:
You've declared your class a but refer to it later as A.
You've written an implementation of a constructor for A without declaring it like a proper forward declaration.
Also, typedef struct is not needed in C++. It is sufficient and encouraged to write:
struct POLLDATA {
...
};

Why should I use a closing bracket in this? [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 have some code which I could not compile it yet. The compiler says there should be a closing bracket, but I can't see a reason for this or place to put it. This is my code:
#include "Player.h"
Player(std::string val){
set_Name(val);
set_Alliance("NONE");
set_LastUpdate();
}
Player(std::string val, std::string ally){
set_Name(val);
set_Alliance(ally);
set_LastUpdate();
}
I have included in Player.h
This is the error:
error: expected ')' before 'val'
This is the prototype for constructor:
Player(std::string);
I am using GNU GCC compiler, under linux(ubuntu)
You are missing the class name from constructor outside the class definition. Try this:
Player::Player(std::string val){ // constructor outside class definition
set_Name(val);
set_Alliance("NONE");
set_LastUpdate();
}
Unverified speculation: With your current code, compiler sees Player(symbol1 symbol2) and takes that as creating object of class Player, and first thing it fails to understand is seeing two symbols as constructor argument, and gives a somewhat misleading error about that.
When you define methods, constructor, destructor etc. outside of the class, remember to tell the compiler that this belongs to the class using the class name following the scope operator :: and the name of the method, constructor, destructor etc with the matching parameters.
As a small example:
class Phone {
string number;
public:
string get_num();
void set_num(string const &num) { number = num; }
};
// Pay attention to this:
// we tell the compiler that get_num belongs to class Phone
string Phone::get_num()
{
return number;
}
int main()
{
Phone p;
p.set_num("123");
cout << p.get_num() << endl;
}