Display Output Data for conversion between 2 Classes - c++

I implemented a conversion for feet to Meters as noted below but I am unable to print out the results in my main. Below is the code generating the error in
Ftr cnum1(2);
Mtr cnum2 = cnum1.toMtr();
std::cout << cnum1.getNum() <<" feet = " << cnum2.getMtrNum() << " meters \n\n";
I’m unable to use the getNum method with cnum2 because getNum is not a method in Mtr. However the results can be accurately displayed in the Ftr.cpp file
#include "Ftr.h"
#include <iostream>
#include <string>
namespace fun::calc
{
Ftr::~Ftr() { }
Ftr::Ftr(double Ftr) noexcept { }
double Ftr::getNum() const noexcept { return m_Num;}
Mtr Ftr::toMtr() const noexcept { return Mtr(m_Num * fInMtr); }
The Ftr header file contains the following:
#ifndef __FTR_H
#define __FTR_H
#include <cstdint>
#include “Mtr.h”
namespace fun::calc
{
class Mtr;
class Ftr
{
double m_Num;
static constexpr double fInMtr = 0.3048;
public:
Ftr() = delete;
explicit Ftr(double Ftr) noexcept;
~Ftr() noexcept;
Ftr(const Ftr &other) = default;
Ftr(Ftr &&other) = default;
double getNum() const noexcept;
Ftr operator+(const Ftr &rhs) const;
Mtr toMtr() const noexcept;
};
}
#endif;
I tried to create a getMtrNum function in the Mtr.cpp as follows:
double Meters:: getMtrNum () const noexcept { return m_mtr;}
I modified main() to use getMtrNum as shown below
Ftr cnum1(2);
Mtr cnum2 = cnum1.toMtr();
std::cout << cnum1.getNum() <<" feet = " << cnum2.getMtrNum() << " meters \n\n";
The results now display 0.0 because n_mtr is initialized to 0.0 in the Mtr.h file
The output produced is :
2 feet = 0 meters
Any suggestions on how to implement this to get the correct results displayed outside of the function definition? Ideally I would like to generate the correct results without having to create getMtrNum. Please provide some guidance on the proper way to get data flowing between the 2 different classes and display the results properly.

If I understood correctly, there are two points you would like to do:
Fix the code so it shows the conversion value
Make the print without creating getMtrNum()
For the second point, if you want to keep your member private, you will need to create a getter/printer function in any case. Probably a bit more elegant if you create an ostream "<<" operator overload. In this way you don't need to use getter function during printing Meters.
Edit: To be more precise getter is still used. Once in the operator overload
std::ostream& operator<<(std::ostream& out, const Meters& m)
{
out << m.Get();
return out;
}
// in main
// std::cout << cnum1.Get() <<" feet = " << cnum2 << " meters \n\n";
A complete working example:
#include <iostream>
class Meters {
public:
Meters(const Meters& m)
:m_Meters(m.m_Meters)
{
}
Meters(double m)
:m_Meters(m)
{
}
double Get() const { return m_Meters; }
private:
double m_Meters{};
};
std::ostream& operator<<(std::ostream& out, const Meters& m)
{
out << m.Get();
return out;
}
class Feet{
public:
Feet(double f)
: m_Feet(f)
{}
static constexpr double fInMtr = 0.3048;
Feet() = default;
Meters ToMeters() const { return Meters(m_Feet * fInMtr); }
double Get() const { return m_Feet; }
private:
double m_Feet{};
};
int main()
{
Feet cnum1(2);
Meters cnum2 = cnum1.ToMeters();
std::cout << cnum1.Get() <<" feet = " << cnum2 << " meters \n\n";
}
I hope, this is what you were looking for.

Related

return float when + class

I was trying to take float + objected class and have the result return as float, however, my code just does not work. I am pretty confused. I have added that overload function as a friend to the class. could anyone explain it to me?
With the best regards
#include <iostream>
#include <cstdint>
using namespace std;
#define MAX_NUM_SENSORS 5
enum { INVALID, TEMPERATURE, HUMIDTY };
// The 'Sensors' structure describes a single sensor, it's type and current value.
// type - describes the type of sensor 0 (INVALID), 1 (TEMPERATURE), 2 (HUMIDITY)
// value - the current value of the sensor.
// valid - set to TRUE if the sensor is valid, should default to FALSE until set up.
class Sensors
{
public:
friend ostream& operator <<(ostream&, const Sensors&);
friend float operator+ (float,const Sensors&);
private:
int type;
float value;
bool valid = false;
};
ostream& operator<<(ostream& OutStream, const Sensors& OutComp)
{
OutStream << " Type: " << (OutComp.type == TEMPERATURE ? "Temperature" : "Humidity");
OutStream << " Value: " << OutComp.value << endl;
return OutStream;
}
float operator+ (float adding, const Sensors& added)
{
float sum;
sum = added.value + adding;
return sum;
}
int main()
{
Sensors tested();
float m = 1.2 + tested;
cout << m;
return 1;
}
I ran your code in godbolt
There is some kind of simple fixes.
int main()
{
Sensors tested();
// ^--- remove this parenthesis (or use braces, it's ambigious)
float m = 1.2 + tested;
// ^----- This is a double, change this to "1.2f"
cout << m;
return 1;
}
Decimal values in code is double by default, you need to add the postfix f to specify that it is a float. Or you could add a definition of operator + with double as a parameter.
Here is a compiling version of your code

addition and subtraction of two numbers using operator overloading

#include<iostream>
using namespace std;
class add
{
private: int a,b;
public: add(int x=0)
{
a=x;
}
add operator+(add const &c) // sub operator-(sub const &c)
{ //{
add sum; // sub diff;
sum.a=a+c.a; // diff.a=a-c.a;
return sum; // return diff
} //}
void print()
{
cout<<"sum: "<<a;
}
};
int main()
{
add a1(10),a2(5); //sub s1(10),s2(5);
add a3=a1+a2; // sub s3=s1-s2;
a3.print(); // s3.print();
return 0;
}
Here I've written seperately but what to do if I need to do both in a single code?
I want a C++ code to perform them simultaneously
You can define any reasonable combination of:
Foo operator+(arg);
Foo operator-(arg);
Foo operator*(arg);
Foo operator/(arg);
And the arg can be another Foo or some other type entirely. For instance:
#include <iostream>
using namespace std;
class Operators {
public:
Operators() = default;
Operators(int v) : value(v) {}
Operators operator+(const Operators &other) {
return Operators{value + other.value};
}
Operators operator+(const int byValue) {
return Operators{value + byValue};
}
Operators operator-(const Operators &other) {
return Operators{value - other.value};
}
Operators operator-(const int byValue) {
return Operators{value - byValue};
}
Operators operator*(const Operators &other) {
return Operators{value * other.value};
}
Operators operator/(const Operators &other) {
return Operators{value / other.value};
}
int value = 0;
};
int main(int, char **) {
Operators first{10};
Operators second{20};
Operators result1 = first + second;
Operators result2 = first * second;
Operators result3 = first * 3;
Operators result4 = second / 2;
cout << "first + second == " << result1.value << endl;
cout << "first * second == " << result2.value << endl;
cout << "first * 3 == " << result3.value << endl;
cout << "first / 2 == " << result4.value << endl;
}
first + second == 30
first * second == 200
first * 3 == 30
first / 2 == 10
You'll see I overwrote operators that take two Operators objects, but I also wrote a few that take an integer argument, too.
I compiled and ran that with:
g++ --std=c++17 Whatever.cpp -o Whatever && Whatever

Copy constructor and cascaded function calls

I ran this example:
#include <cstdlib>
#include <iostream>
#include <istream>
#include <ostream>
using namespace std;
class Weight {
int k;
char a[100];
public:
Weight(int kilos = 0)
:k(kilos) {}
Weight(const Weight& w)
: k(w.k) {
for(int i = 0; i < 100; ++i) this->a[i] = 'a';
cout << "WCC\n";
}
friend Weight operator+(const Weight& a, const Weight& b);
Weight& operator=(const Weight & w) {
this->k = w.k;
return *this;
}
friend ostream& operator<<(ostream&, const Weight&);
};
Weight operator+(const Weight& a, const Weight& b) {
cout << "FP\n";
int newkg = a.k + b.k;
return Weight(newkg);
}
ostream& operator<<(ostream& out, const Weight& w) {
out << w.k << " KGs";
return out;
}
class Container{
Weight w;
static Weight totalW;
static int count;
public:
Container(){++count;}
~Container(){cout << "CD\n";}
Container& add(Weight weight) {
this->w = this->w + weight;
totalW = totalW + weight;
cout << "Just added a new item that weighs " << weight << endl;
return *this;
}
static void print() {
cout << "We have " << count << " Containers with a total weight "
<< totalW << endl;
}
friend ostream& operator<<(ostream&, const Container&);
};
Weight Container::totalW;
int Container::count = 0;
ostream& operator<<(ostream& out, const Container& c){
out << "This container's " << c.w;
return out;
}
int main(int argc, char** argv) {
Container c1;
Weight *w1 = new Weight(1);
Weight *w2 = new Weight(2);
Weight *w3 = new Weight(3);
cout << "Adding items to container...\n";
c1.add(*w1).add(*w2).add(*w3);
cout << c1 << endl;
Container::print();
return 0;
}
And I got this output:
Adding items to container...
WCC
WCC
WCC
FP
FP
Just added a new item that weighs 1 KGs
FP
FP
Just added a new item that weighs 2 KGs
FP
FP
Just added a new item that weighs 3 KGs
This container's 6 KGs
We have 1 Containers with a total weight 6 KGs
CD
You can see that the copy constructor for the Weight class was called three times (Output lines 2-4) before any of the cascaded functions was called. I always thought that the left most function call will be performed before any copy constructor is called up to setup the second function call.
To be more specific, I thought this what should have happened:
WCC -> c1.add(*w1) -> WCC -> .add(*w2) -> WCC -> .add(*w3).
I thought this was necessary because the function argument will be stored in the function's stack frame. So, a stack frame needs to be setup before the copy constructor for the argument is called. Apparently, I am mistaken.
This makes me think that function arguments are store somewhere else other than the stack frame. So, where?
Do not mind the horrific coding style. This, obviously, is not meant to be in production code.
I think this is a basic compiler optimization. Since there's no requirement when a function's parameters should be initialized from supplied arguments, a compiler can do necessary optimization by rearranging them. That's why you see the copy constructors called all at once.

Getting unresolved external error when operator overloading, even after defining all the methods

EDIT: need to delete post -- problem was trivial (typographical error) and won't be of any help to others
I'm getting errorLNK2019, the unresolved external error, when trying to use an operator overload in one of my cpp files. I've looked all over, and many people have been able to fix the problem by making sure to define every single method in their class prototypes.
I think this has to do a lot with my project design to be honest, but I really can't pinpoint exactly why this error is happening
Here's the code:
//a.cpp
//
// ... skipped all code to bottom to where i modified it
//OVERLOADED FUNCTIONS
int operator+(const int n, const a& entry){
return n + entry.getTime();
}
ostream& operator<<(ostream & out, const a& entry){
out << entry.getTitle() << " by " << entry.getArtist()
<< " (" << entry.getTime() << ") ";
return out;
}
//*********************************************************
// a.h
//... only posting what I changed
//
// Inside the class..
class a
{
public:
friend ostream& operator<<(const ostream& out, const a& entry);
friend int operator+(const int n, const a& entry);
//..
//.. SNIPPED
//..
}
I run into the error when I try to output a b object in the show() method.
//b.cpp
#include "b.h"
b b::etnsl(const int &indexOfItemToAdd) const{
if (originalObjects != NULL && indexOfItemToAdd >= (*originalObjects).size()){
throw "Index out of bounds";
}
b x(originalObjects);
vector<int> *iCopy = x.getIndices();
(*iCopy) = indices;
iCopy->push_back(indexOfItemToAdd);
x.setSum(sum + (*originalObjects)[indexOfItemToAdd].getTime());
return x;
}
void b::show() const{
cout << " Item at loc " << "0x" << this << ":" << endl;
//int j = indices.size();
//if (j == 0)
if (size == 0)
cout << " Empty item." << endl;
else{
for (int i = 0; i < size; i++) //ERROR IN LOOP
cout << " Index " << indices[i] << " : " << (*originalObjects)[indices[i]] << endl;
}
}
int b::getSum() const{
return sum;
}
void b::setSum(const int& num){
sum = num;
}
vector<int>* b::getIndices(){
return &indices;
}
//*********************************************************
//b header class
#ifndef B_H
#define B_H
#include <iostream>
#include <vector>
#include "a.h"
using namespace std;
class b{
private:
int sum, size;
vector <a> *originalObjects;
vector <int> indices;
public:
b(vector<a> *orig = NULL) //counts as 2 constructors: default and a custom one.
: sum(0), originalObjects(orig), size(indices.size()) {
}
b etnsl(const int &indexOfItemToAdd) const;
void show() const;
int getSum() const;
void setSum(const int& num);
vector<int> *getIndices();
};
#endif
ostream& operator<<(ostream & out, const iTunesEntry& tune)
is not same as
ostream& operator<<(const ostream& out, const iTunesEntry& entry);
// ~~~~~
inside the iTunesEntry class (friend method)
And const shouldn't be used as you will have to modify the out object of ostream

Templates C++ error : could not deduce template argument

I am trying ot add a function template that will print if it contains precision values or valves and the value. The rest of the program works except this function. I am not sure what I am doing wrong but the error I recieve is:
error C2784: 'void printInstrumentDetail(const I *const )' : could not deduce template argument for 'const I *const ' from 'std::vector<_Ty>'
#include <iostream>
#include <vector>
#include <iomanip>
#include <string>
#include "Instruments.h"
#include "Brass.h"
#include "Strings.h"
using namespace std;
//template<typename I> <---Problem
//void printInstrumentDetail(const I * const a)
//{
// for (size_t i = 0; i < 6; i ++)
// {
// cout << "The details for " << a[i]->getName()
// << ": " << a[i]->print();
// }
//}
int main()
{
double total = 0;
Strings violin("Violin", 553.90, 3);
Strings cello("Cello", 876.45, 3);
Strings viola("Viola", 200.50, 23);
Brass tuba("Tuba", 1400.10, 1.23);
Brass trumpet("Trumpet", 500.00, 4.32);
Brass sax("Sax", 674.78, .99);
vector <Instruments *> band(6);
band[0] = &violin;
band[1] = &tuba;
band[2] = &cello;
band[3] = &trumpet;
band[4] = &viola;
band[5] = &sax;
cout << fixed << setprecision(2);
cout << "The instruments in the band are:\n";
//Get name and cost of each
for (size_t i = 0; i < 6; i ++)
{
cout << band[i]->getName() << " $"
<< band[i]->getCost() << endl;
}
cout << "\nThen band is warming up..." << endl;
//Get descrition of how sound is made of each
for (size_t i = 0; i < 6; i ++)
{
cout << "This " << band[i]->getName()
<< " makes sounds by " ;
band[i]->playSound();
}
cout << "\nTotal cost of the band is: $" ;
//Get total cost of all instruments
for (size_t i = 0; i < 6; i ++)
{
total = band[i]->getCost() + total;
}
cout << total << endl;
//printInstrumentDetail(band); <--Problem
return 0;
}
Here's the base class:
#ifndef INSTRUMENTS_H
#define INSTRUMENTS_H
#include <string>
using namespace std;
class Instruments
{
public:
Instruments(string, double);
void setName(string);
virtual string getName();
void setCost(double);
virtual double getCost();
virtual void print();
virtual void playSound();
private:
string name;
double cost;
};
#endif
#include <iostream>
#include "Instruments.h"
using namespace std;
Instruments::Instruments(string n, double c)
{
name = n;
cost = c;
}
void Instruments::setName(string n)
{
name = n;
}
string Instruments::getName()
{
return name;
}
void Instruments::setCost(double c)
{
cost = c;
}
double Instruments::getCost()
{
return cost;
}
void Instruments::print()
{
}
void Instruments::playSound()
{
//empty
}
Derived class Bass:
#ifndef BRASS_H
#define BRASS_H
#include <string>
#include "Instruments.h"
using namespace std;
class Brass : public Instruments
{
public:
Brass(string, double, double);
void setPrecisionValue(double);
double getPrecisionValue();
void print() ;
void playSound();
private:
double precision;
string sound;
};
#endif
#include <iostream>
#include "Brass.h"
using namespace std;
Brass::Brass(string n, double c, double p)
:Instruments(n, c)
{
precision = p;
}
void Brass::setPrecisionValue(double p)
{
precision = p;
}
double Brass::getPrecisionValue()
{
return precision;
}
void Brass::print()
{
cout << getPrecisionValue() << endl;
}
void Brass::playSound()
{
cout << "blowing in a mouthpiece." << endl;
Instruments::playSound();
}
Derived class Strings:
#ifndef STRINGS_H
#define STRINGS_H
#include <string>
#include "Instruments.h"
using namespace std;
class Strings : public Instruments
{
public:
Strings(string, double, int);
void setValves(int);
int getValves();
void print();
void playSound();
private:
int valves;
};
#endif
#include <iostream>
#include "Strings.h"
using namespace std;
Strings::Strings(string n, double c, int v)
:Instruments(n, c)
{
valves = v;
}
void Strings::setValves(int v)
{
valves = v;
}
int Strings::getValves()
{
return valves;
}
void Strings::print()
{
cout<< getValves() << endl;
}
void Strings::playSound()
{
cout << "striking with a bow." << endl;
Instruments::playSound();
}
Well, the problem is that your template requires a pointer:
template<typename I>
void printInstrumentDetail(const I * const a);
but you're giving it a vector, not a pointer:
vector <Instruments *> band(6);
...
printInstrumentDetail(band);
You can hack your way around this by passing a pointer to the printInstrumentDetail function, like so:
printInstrumentDetail(&band[0]);
But really, you'd be much better off modifying printInstrumentDetail to take a container or a pair of iterators:
template <typename ContainerT>
void printInstrumentDetail(const ContainerT& a)
or
template <typename IteratorT>
void printInstrumentDetail(IteratorT first, IteratorT last)
with the appropriate modifications to the definition of the function.
Pass the pointer to vector
printInstrumentDetail(&band);
and inside printInstrumentDetail
(*a)[i]->getName();
Well, first off I don't believe you can pass a vector as a const * I const at
printInstrumentDetail(band);
Vector cannot be just cast to a pointer. One working solution would be something like:
template <typename T>
void printInstrumentDetail( const std::vector<T*>& band )
{
for ( size_t i = 0; i < band.size(); ++i )
cout << "The details for " << band[i]->getName()
<< ": " << band[i]->print();
}
And there are many others, including iterators, functors, STL algorithms, etc.
You are trying to pass an object to an interface that wants a pointer.
void printInstrumentDetail(const I * const a)
Convert this to a reference.
void printInstrumentDetail(I const I& a)
But to conform to the pattern that is common in C++. You should pass the beginning and end of the sequence as parameters. ie change your function to take itertors rather than a pointer.
Instead of passing the pointer:
printInstrumentDetail(const I * const a)
you can pass the reference:
printInstrumentDetail(const I& a)
Everything else stays unchanged.
First of all, there seems to be no reason for PrintInstrumentDetail to be a template at all -- it works with pointers to the base class, and unless you're likely to have other types with getName() and print() members to which it might be applied, it can/could/should just work with pointers to the base class.
Second, I'd think hard about changing how you do the job. Instead of a member function in each Instrument, and PrintInstrumentDetail to loop over all the instruments, I'd think hard about defining operator<< for Instrument, and using a standard algorithm to print out the details.
Looking at it, I think a few other things should change as well. First of all, unless you're dealing with really unusual instruments, the number of valves on a brass instrument is fixed forever -- so it should NOT have a SetValve() member. Rather, the number of valves should be set during construction, but not be open to change afterwards.
String instruments don't have valves at all (at least most normal ones don't), so they shouldn't have SetValves(), GetValves(), or anything else related to valves.
Likewise, unless you're doing something pretty unusual, the cost of an instrument can never change -- you paid what you paid, so the cost should be set during construction, and not open to later alteration.
Edit: one other thing: instead of hard-coding 6 everywhere, use band.size() to loop over all the instruments in the band.