I created two classes and a constructor in each. Type followed a new class and constructors friends functions of the classes before.
#include <iostream>
using namespace std;
class clsAtmosfericConditions;
class clsDensity{
float density;
public:
clsDensity(){}
clsDensity(float densidad){
density = densidad;
}
friend istream& operator >>(istream &i, clsDensity &e);
friend ostream& operator <<(ostream &o, const clsDensity &s);
};
istream& operator >>(istream &i, clsDensity &e){
char sign;
i >> e.density >> sign >> sign >> sign >> sign >> sign >> sign;
return i;
}
ostream& operator <<(ostream &o, const clsDensity &s){
o << s.density << " Kg/m^3";
return o;
}
class clsDynamicViscocity{
double dynamicViscocity;
public:
clsDynamicViscocity(){}
clsDynamicViscocity(double viscocidadDinamica){
dynamicViscocity = viscocidadDinamica;
}
friend istream& operator >>(istream &i, clsDynamicViscocity &e);
friend ostream& operator <<(ostream &o, const clsDynamicViscocity &s);
};
istream& operator >>(istream &i, clsDynamicViscocity &e){
char sign;
i >> e.dynamicViscocity >> sign >> sign >> sign >> sign >> sign;
return i;
}
ostream& operator <<(ostream &o, const clsDynamicViscocity &s){
o << s.dynamicViscocity << " N/m^2";
return o;
}
class clsAtmosfericConditions{
friend clsDynamicViscocity::clsDynamicViscocity(double viscocidadDinamica);
friend clsDensity::clsDensity(float densidad);
public:
float kinematicViscocity();
};
float kinematicViscocity(){
float kinematicViscocity;
kinematicViscocity = dynamicViscocity/density; //Here is where IDE gives me the error
return kinematicViscocity;
}
The IDE displays an error in the function: error: 'dynamicViscocity' undeclares (first use this function)
I checked on some websites and I see no need to pass values by reference builder when you do the operation.
Couple of problems here.
dynamicViscocity is a member of class clsDynamicViscocity. kinematicViscocity is not a member of any class, but I suspect is is intended to be a member of clsAtmosfericConditions. Regardless, kinematicViscocity is not a member of clsDynamicViscocity, so in order to operate on dynamicViscocity, it needs an object of type clsDynamicViscocity to provide dynamicViscocity.
Second, the visibility (public, private, protected) of dynamicViscocity is not specified, so C++ defaults to the most restrictive, private. A private member cannot be seen except by the object and those the object has defined as friends.
So kinematicViscocity has no dynamicViscocity and even if it did, it cannot see dynamicViscocity.
Suggested solution
Change the definition of kinematicViscocity to
float clsAtmosfericConditions::kinematicViscocity(const clsDynamicViscocity & vis,
const clsDensity & den)
{
float kinematicViscocity;
kinematicViscocity = vis.getDynamicViscocity() / den.getDensity();
return kinematicViscocity;
}
to provide a clsDynamicViscocity to kinematicViscocity and add a getter function
double getDynamicViscocity() const
{
return dynamicViscocity;
}
to clsDynamicViscocity.
The same needs to be done to access density from clsDensity.
EDIT
Waaaait a second...
Finally figured out what you are trying to do here:
friend clsDynamicViscocity::clsDynamicViscocity(double viscocidadDinamica);
friend clsDensity::clsDensity(float densidad);
A class declares who they will allow to see and use their hidden internals. A class cannot declare who's hidden internals they can see. Think of it this way, Bob can be friends with Alice and show her his secrets, but Bob cannot force Alice to be his friend and show him her secrets. Alice has to make that decision herself.
What the above means is the two methods can can violate encapsulation and see the hidden internals of clsAtmosfericConditions. clsAtmosfericConditions cannot however see the internals of clsDynamicViscocity or clsDensity.
clsDynamicViscocity and clsDensity have to friend class clsAtmosfericConditions to allow clsAtmosfericConditions to see into them, not the other way around.
So
clsDensity()
{
friend class clsAtmosfericConditions;
...
}
and
clsDynamicViscocity()
{
friend class clsAtmosfericConditions;
...
}
Now change kinematicViscocity to look like this:
float clsAtmosfericConditions::kinematicViscocity(const clsDynamicViscocity & vis,
const clsDensity & den)
{
float kinematicViscocity;
kinematicViscocity = vis.dynamicViscocity / den.density;
return kinematicViscocity;
}
and you are golden.
The original solution with the getters is a better solution as it requires no friends whatsoever and is much less tightly coupled. The guts of clsDynamicViscocity and clsDensity can be radically changed without breaking clsAtmosfericConditions so long as the getter function prototypes remain the same and clsAtmosfericConditions is granted no more access to clsDynamicViscocity and clsDensity than is required to get data.
Related
If i want to overload the operator ">>" and this is the line inside my .h file
friend istream &operator >> (istream& input,const Money&m2);
Do I want for instance
friend istream &operator >> (istream& input,const Money&m2){
input >> m2.dollar;
return input;
}
into my header file or into my class file. If i were to put it into my class file how would the function be called? Would something like this be okay?
const Money Money::&operator >> (istream& input,const Money&m2)
The class name is "Money.cpp"
The input streaming operator takes a reference to a non-const std::istream, and a reference to a non-const object into which the data is to be read. You can define it as a friend of the class for efficiency (direct access to the member variables), but if you already provide efficient mechanisms for setting those values, you may want to consider whether it needs to be a friend at all.
In the example below, I define a class Money, which represents some value (as a double-precision floating-point value, which is pretty bad, but just an example) and the ISO currency code (as a std::string). I then define an input streaming operator that reads input in the format "13.99 GBP" and an output streaming operator that writes the values in the same format.
Live example: http://coliru.stacked-crooked.com/a/d3e24b4fd697f773
money.hpp
class Money {
public:
Money(double value, const std::string& code);
const std::string& currencyCode() const;
double value() const;
friend std::istream& operator>>(std::istream&, Money&);
private:
double value_;
std::string code_;
};
std::istream& operator>>(std::istream& in, Money& m);
std::ostream& operator<<(std::ostream& out, const Money& m);
money.cpp
Money::Money(double value, const std::string& code)
: value_(value), code_(code) {}
const std::string& Money::currencyCode() const {
return code_;
}
double Money::value() const {
return value_;
}
std::istream& operator>>(std::istream& in, Money &m) {
in >> m.value_ >> m.code_;
return in;
}
std::ostream& operator<<(std::ostream& out, const Money& m) {
out << m.value() << " " << m.currencyCode();
return out;
}
Some points to bear in mind:
In general, the output streaming operator need not be a friend; there is usually a way to access the information it needs through the public member functions of the class, without losing efficiency.
The input streaming operator is a friend only for efficiency reasons; we can stream directly into the member variables.
For the input streaming operator, the second parameter (the object you're reading into) must not be const - an input operation changes the object being read into.
For the output streaming operator, the second parameter (the object you're writing out) should be const - an output operation should not change the object being written out.
If the constructor performs some non-trivial validation (e.g. checking that the std::string contains a valid ISO currency code), we should not bypass that validation by reading directly into the member variable in our input streaming operator. Instead, we should read into a local double and a local string, then construct a Money object, handing validation off to the already-written constructor (see the example below; the header is identical, except for removing the friend declaration from the class).
Live example: http://coliru.stacked-crooked.com/a/233ac7c17e51f612
money.cpp (validation in constructor)
Money::Money(double value, const std::string& code)
: value_(value), code_(code) {
if (code_ != "GBP") throw std::runtime_error("Must be GBP");
}
const std::string& Money::currencyCode() const {
return code_;
}
double Money::value() const {
return value_;
}
std::istream& operator>>(std::istream& in, Money &m) {
double value(0.0);
std::string code;
in >> value >> code;
m = Money(value, code);
return in;
}
std::ostream& operator<<(std::ostream& out, const Money& m) {
out << m.value() << " " << m.currencyCode();
return out;
}
If you put it in your header any change in the function definition requires recompilation of any files that include it. If you define it in the .cpp file then you don't and the linker will sort out calling it.
I don't know what is bothering you so have this example and see if it clears your doubt.
Run Here: http://ideone.com/K90L13
.h
#include <iostream>
#include <istream>
using namespace std;
class A{
int p;
public:
friend istream & operator >> (istream&,A&);
friend ostream & operator << (ostream&,A&);
};
.cpp
istream & operator >> (istream &input, A &obj){
input >> obj.p;
return input;
}
ostream & operator << (ostream &output, A &obj){
output << obj.p;
return output;
}
int main(){
A a;
cin >> a;
cout << a;
}
answered.
Function name in class field should be
std::istream &operator >> (istream& input,const Money&m2){}
I'm currently working on a C++ assignment and I have 3 different types of objects. Customer, Hire and Tour. When I create a object now I do the following, I read the data from a file and then do the following,
Customer* cust = new Customer(custId, Name, ...);
However the requirement is to use >> operators to read this information into objects. Also use << write it back. How can I achieve this?
Many thanks :)
First of all, there is likely no need for your to create objects on the heap.
After you've made those corrections, you can overload the insertion and extraction operators:
// assuming you declare these operators as friends of Customer
std::ostream& operator<<(std::ostream& os, const Customer& c)
{
os << c.data;
return os;
}
std::istream& operator>>(std::istream& is, Customer& c)
{
is >> c.data;
return is;
}
Well here is a really good reference (apparently not that good because I had to fix some of the code) for overloading the io operators. I can't tell you much more with out knowing the details of your class, however I can say that the beauty of the stream operators is that they provide an interface to any stream type object not just stdin and stdout. Here is a little example from the site:
#include
using namespace std;
class Point
{
private:
double m_dX, m_dY, m_dZ;
public:
Point(double dX=0.0, double dY=0.0, double dZ=0.0)
{
m_dX = dX;
m_dY = dY;
m_dZ = dZ;
}
friend ostream& operator<< (ostream &out, Point &cPoint);
friend istream& operator>> (istream &in, Point &cPoint);
double GetX() { return m_dX; }
double GetY() { return m_dY; }
double GetZ() { return m_dZ; }
};
ostream& operator<< (ostream &out, Point &cPoint)
{
// Since operator<< is a friend of the Point class, we can access
// Point's members directly.
out << cPoint.m_dX << " " << cPoint.m_dY << " " << cPoint.m_dZ << std::endl;
return out;
}
istream& operator>> (istream &in, Point &cPoint)
{
in >> cPoint.m_dX;
in >> cPoint.m_dY;
in >> cPoint.m_dZ;
return in;
}
IMO the best way to think about overloading these operators is to leverage previously written >> and << and that way you sort of build a chain and it becomes extremely simple and convenient to implement these operators.
I'm in a programming class and need overloading explained to me. Simple question so hopefully I'll get an answer pretty quick. My understanding is that overloading an operator allows it to be used on a class. If that is true, then how would I overload >> to work with a class? I'm working on a small program to test out this idea and i'll post it here
#include <iostream>
#include <cstdlib>
#include "data.h"
using namespace std;
int main()
{
data obj;
cout << "What is the Number?" << endl;
cin >> obj;
system("pause");
return 0;
}
class data
{
public:
data operator >> (int);
private:
};
This page tells you mostly everything you need to know about operator overloading.
In short, nearly every operator in C++ can be overloaded for user-defined types. Some operators, like +, -, or >> must be defined outside of a class since they are free-standing, whereas others like copy assignment (=), must be defined within.
For your case, overloading the >> operator can be done in the following manner:
istream& operator>>(istream& in, data& d){
// Code here
return in;
}
Where it says "Code here", place the code you need to read into the data object.
For example, let us pretend that we were reading into a Point object with an x coordinate and a y coordinate. It is formatted in the stream like so: "(x,y)". The operator overload might look like this:
istream& operator>>(istream& in, Point& p){
char c;
in >> c;
if(c != '('){
in.clear(ios_base::failbit);
return in;
}
in >> p.x >> c >> p.y >> c;
return in;
}
This is just an example with minimal format checking, but hopefully it is enough to get you started.
Note that if members in your class are private, then you should friend the istream operator in the class definition:
class data{
...
public:
friend istream& operator>>(istream&, data&);
}
case1: no need to access private data
data.h.
class data {
public:
int i;
};
std::ostream& operator>> (std::istream&, data&); // better make operator >>
// a nonmember function
// if it doesn't need access
// to private data
data.cpp
#include "data.h"
std::istream& operator>> (std::istream& is, data& d) {
is>>d.i; // here we do some logic, we do what it means to do >> on
return is; // an instance of your data class and return reference to istream
}
case2: there is a need to access private data
data.h.
class data {
private:
int i;
friend std::ostream& operator>> (std::istream&, data&);
};
data.cpp
#include "data.h"
std::istream& operator>> (std::istream& is, data& d) {
is>>d.i; // here we do some logic, we do what it means to do >> on
return is; // an instance of your data class and return reference to istream
}
If you want to bolster your understanding of what operator overloading is, consider that essentially all operators on objects (such as "+", "++", "==", "!=", etc) are member functions.
Challenge yourself to recognize Obj a, b; a = b; as Obj a; Obj b; a.operator=(b);.
Overloading is purely providing a non-default implementation.
Here is a [terrible] overload of the cast-to-const-char* operator:
class BadWolf {
const char* m_text;
public:
BadWolf(const char* text) : m_text(text) {}
// if you really want the original text and ask for it with this function...
const char* tardisTranslation() const { return m_text; }
// but if you try to use me as a const char*...
operator const char* () const { return "bad wolf"; }
};
int main(int argc, const char* argv[]) {
BadWolf message("hello, sweetie");
std::cout << "Message reads: " << (const char*)message << std::endl;
std::cout << "Tardis translation: " << message.tardisTranslaction() << std::endl;
return 0;
}
I think this is what you want.
class data
{
friend istream& operator>>( istream&, data& );
private:
int data;
};
istream& operator>>( istream& in, data& d )
{
return in >> d.data;
}
hey, i got something that i cannot understand ,there are two types of solutions for overloading this operator 1 is including the friend at the start of the method and the other 1 goes without the friend.
i would very much like if some1 explain whats the difference between them advantages / disadvantages.
for example overloading the operator << in class rational:
class Rational:
{
private: int m_t,m_b;
...
friend ostream& operator<<(ostream& out,const Rational& r) // option 1
{ return out << r.m_t << "/" <<r.m_b;} // continue of option 1
ostream& operator<<(ostream& out,const Rational& r){return r.print();} // option 2
virtual ostream& print(ostream& out) const // continue of option 2
{ //
return out<<m_t << "/" << m_b;
} //
};
i was told that the second option isnt correct , if some1 can correct me about it i would much appriciate it.
thanks in advance.
The short answer: Option #2 actually isn't an option, but a syntax error, because it tries to define a binary operator as a member passing two operands.
The somewhat longer answer: If you make the second operand a free function (not a member of the class), this will work. Which one is preferable depends on the circumstances and your preferences. For starters: The disadvantage of the first is that it allows operator<< to access everything in Rational (including private helper functions), while the disadvantage of the second is that you introduce a function to the class' public API that nobody needs.
operator<< (for ostream) needs to be a free function (since the left-hand argument is a stream, not your class).
The friend keyword makes it a free function (a free function that has access to the private members).
However, if this functionality can be implemented in terms of the public interface, it is better to do so and just use a non-friend free function.
class Rational:
{
private: int m_t,m_b;
public:
...
virtual ostream& print(ostream& out) const
{
return out<<m_t << "/" << m_b;
}
};
ostream& operator<<(ostream& out,const Rational& r)
{
return r.print(out);
}
Consider a function that should output the num and den of Rational:
ostream& operator<<(ostream& out, const Rational& r)
{
return out;
}
Unfortunately, this is just a global function. Like any other global function, it cannot access the private members of Rational. To make it work with Rational objects, you need to make it friend of Rational:
class Rational
{
private: int m_t,m_b;
// ...
friend ostream& operator<<(ostream& out, const Rational& r);
};
ostream& operator<<(ostream& out, const Rational& r)
{
out << r.m_t << "/" <<r.m_b;
return out;
}
The friend ostream& operator<<(ostream& out, const Rational& r); inside Rational class indicates that ostream& operator<<(ostream& out, const Rational& r) function can directly use Rational's private members.
Now when you write:
Rational r(1, 2); // Say, it sets num and den
cout << r;
the following function call is made:
operator<<(cout, r);
Can you write operator<< as a member function of Rational? That's simply not possible because of the above conversion where cout has to be first parameter. If you make operator<< as a member of Rational:
class Rational
{
private: int m_t,m_b;
// ...
public:
ostream& operator<<(ostream& out) const
{
out << r.m_t << "/" <<r.m_b;
return out;
}
};
you need to call it this way:
Rational r(1, 2);
r.operator<<(cout);
which is ugly.
I'm a bit confused about how to overload the stream operators for my class in C++, since it seems they are functions on the stream classes, not on my class. What's the normal way to do this? At the moment, for the "get from" operator, I have a definition
istream& operator>>(istream& is, Thing& thing) { // etc...
which works. It's not mentioned in the definition of the Thing class. I want it to be able to access members of my Thing class in its implementation - how do I do this?
Your implementation is fine. The only additional step you need to perform is to declare your operator as a friend in Thing:
class Thing {
public:
friend istream& operator>>(istream&, Thing&);
...
}
The other answers are right. In case it helps you, here's a code example (source):
class MyClass {
int x, y;
public:
MyClass(int i, int j) {
x = i;
y = j;
}
friend ostream &operator<<(ostream &stream, MyClass ob);
friend istream &operator>>(istream &stream, MyClass &ob);
};
ostream &operator<<(ostream &stream, MyClass ob)
{
stream << ob.x << ' ' << ob.y << '\n';
return stream;
}
istream &operator>>(istream &stream, MyClass &ob)
{
stream >> ob.x >> ob.y;
return stream;
}
You make your operator>> a friend of the Thing class.
There are several approaches and the right one really depends on what the class does.
Quite often it makes sense to have public API that allows reading the information, in which case the streaming operators do not need to access privates.
Probably the most popular approach is declaring the streaming functions friends of the class.
My favorite is providing a public Boost.Serialization style template function that can be used for streaming either way, as well as for other things.