I need to implement the class Multiplier for a school exercise, but I do not understand how the teacher was able to call prod() without calling its inputs.
The goal of the code is to read a sequence of integers until the product of their absolute values is greater than 200.
Can somebody help me understanding please?
Here is the code:
#include <iostream>
using namespace std;
int main()
{
Product mult(200);
cout << "Enter numbers: " << endl;
do{
cin >> mult;
} while(!mult.exceed_limit());
cout << "The absolute values product is " << mult() << " . " << endl;
return 0;
}
A class can implement the "call" operation by overloading the operator() member function.
For example
class MyType {
public:
void operator()(int param) const {
std::cout << "MyType(int) called with: " << param << "\n";
}
void operator()() const {
std::cout << "MyType() called\n";
}
};
int main() {
MyType instance;
instance(12);
instance();
return 0;
}
Multiplier prod(100); - Multiplier must have defined a constructor that takes an integer as input, eg:
class Multiplier
{
...
public:
Multiplier(int value);
...
};
cin >> prod - Multiplier must have overloaded operator>> for input, eg:
class Multiplier
{
...
};
istream& operator>>(istream&, Multiplier&);
prod.limit_exceeded() - Multiplier must have defined a member limit_exceeded() method, eg:
class Multiplier
{
...
public:
bool limit_exceeded() const;
...
};
cout << prod() - Multiplier must have overloaded operator() (and the return value is then streamed to cout via operator<<), eg:
class Multiplier
{
...
public:
int operator()() const;
...
};
Lets see what we need
int main()
{
Multiplier prod(3);
A constructor. The parameter is probably the number of factors to be multiplied.
std::cout << "Enter numbers: " << std::endl;
do{
std::cin >> prod;
A way to "input" the factors.
} while(!prod.limit_exceeded());
A method to see if the entered factors equals the number of desired factors.
std::cout << "The product of the absolute values is " << prod() << " . " << std::endl;
A call operator that returns the resulting product.
return 0;
}
So lets do that:
struct Multiplier {
Multiplier(size_t n) : max_factors(n),num_factors(0),product(1) {}
size_t max_factors;
size_t num_factors;
double product;
double operator()() const { return product;}
bool limit_exceeded() const { return max_factors <= num_factors;}
};
Constructor takes number of factors, product holds the result, operator() returns the result and limit_exceeded() checks if all factors have been entered. Finally, a an overload for operator>> to read the factors:
std::istream& operator>>(std::istream& in, Multiplier& m){
double x;
if (in >> x) {
m.product *= x;
++m.num_factors;
}
return in;
}
It is a bit uncommon for std::cin >> prod; to not read prod but instead to modify prod, but thats fine.
Live Demo
Related
I am a beginner in programming.I have a problem. I am trying to code the Enigma machine. I have two classes. One for Enigma, one for rotors. Rotors are small parts of the enigma machine, that doesn't matter for the problem. My problem is the error. I cannot cout, the function cout << rotors[0].GetRotor(); which should return my vector of integers. I have no idea why is that. I don't need that to my program, but I'm not sure if my adding rotor to enigma void AddRotor(Rotor rotor) { rotors.push_back(rotor); }function, called in "TakeRotors" function, works right. In my opinion, it should work well, but I can't check it. Debugger, unfortunately, doesn't show any values of vector<Rotor> rotors; permutation so I am not sure :( Any help would be great. Thank You.
Here's my full, needed code :)
#include <iostream>
#include <vector>
using namespace std;
class Rotor {
public:
vector <int> permutation;
int position;
Rotor(vector<int> permutation) {
position = 0;
permutation;
}
vector<int> GetRotor() const {
return permutation;
}
};
class Enigma {
public:
vector<Rotor> rotors;
void AddRotor(Rotor rotor) {
rotors.push_back(rotor);
}
void PrintRotor(const vector<Rotor>& rotors) {
cout << rotors[0].GetRotor(); // Error right here
cout << rotors[0].position;
}
void setupRotor(int index) {
Rotor rotor = rotors[index];
}
void MoveRotor(int index) {
rotors[index].position++;
cout << "Before" << endl;
// cout << rotors[index].permutation.data << ' ';
Enigma::PrintRotor(rotors);
rotate(rotors[index].permutation.begin(), rotors[index].permutation.begin() + rotors[index].permutation.size(), rotors[index].permutation.end());
cout << "After" << endl;
Enigma::PrintRotor(rotors);
}
};
vector<int> take_numbers(int number) {
vector<int> numbers;
for (int i = 0; i < number; i++) {
int number;
cin >> number;
numbers.push_back(number);
}
return numbers;
}
void take_rotors(int number_letters, Enigma* enigma) {
int numberOfRotors;
// int numberOfNotch, positionOfNotch;
cout << "Give number of Rotors" << endl;
cin >> numberOfRotors;
for (int i=0; i < numberOfRotors; i++) {
vector<int> permutation = take_numbers(number_letters);
Rotor Rotor(permutation);
enigma->AddRotor(Rotor); // I am not sure if it adds Rotors fine.
}
}
int main()
{
Enigma enigma;
int number_letters, move_rotor;
cout << "Give number of letters in alphabet" << endl;
cin >> number_letters;
take_rotors(number_letters, &enigma);
// take_reflectors(number_letters, &enigma);
cout << "Which rotor do you want to move (index)" << endl;
cin >> move_rotor;
enigma.MoveRotor(move_rotor);
return 0;
}
There is no operator<<(std::ostream&,const std::vector<int>&) if you want it you need to supply your own. However, overloading operators for types you don't own is not recommended, so I would rather write a function:
void print_vector(std::ostream& out, const std::vector<int>& vect) {
for (int i : vect) {
out << i << '\n';
}
}
That you can call like this
print_vector(std::cout, rotors[0].GetRotor());
Alternatively you can supply an overload for << that prints all the Rotor:
std::ostream& operator<<(std::ostream&,const Rotor& rotor) {
out << rotor.position;
for (auto& i : rotor.GetRotor()) {
out << i;
}
// modify and add more to your likings
return out;
}
Once you have that you can also provide an overload to print a vector of rotors that you can use in Enigma::PrintRotor (which currently only prints the first element of the vector):
std::ostream& operator<<(std::ostream& out,const std::vector<Rotor>& rotors) {
for (const auto& r : rotors) {
out << r << '\n';
}
return out;
}
PS your naming is a little confusing. A Rotor has a GetRotor which returns permutations !?! I strongly suggest to use better names. If I have Rotor r; then r is the Rotor and it is not obvious what a GetRotor will do. Maybe rename it to GetPermutations?
When I am executing this, a garbage value is coming with account balance info. Can anyone help me why?
#include<bits/stdc++.h>
using namespace std;
class Bankaccount
{
public:
int accnumber,accbalance;
int display()
{
cout<<"Account number is: "<<accnumber;
cout<<"\nAccount balance is: "<<accbalance;
}
};
int main() {
Bankaccount a;
Bankaccount b;
a.accnumber = 123456;
a.accbalance =50;
b.accnumber = 67890;
b.accbalance = 2000;
cout<<"Account details of A\n\n"<<a.display()<<endl;
cout<<"\nAccount details of B\n\n"<<b.display();
return 0;
}
The function display() should return void in this case. Your version has in its signature that it returns int, but then you don't return anything. This leads to undefined behavior.
Also it is bad practice to use using namespace std and #include<bits/stdc++.h>.
Read up here Why is "using namespace std;" considered bad practice?
And here How does #include <bits/stdc++.h> work in C++?
#include <iostream>
class Bankaccount
{
public:
int accnumber, accbalance;
void display()
{
std::cout << "Account number is: " << accnumber << "\n";
std::cout << "Account balance is: " << accbalance << "\n";
}
};
int main()
{
Bankaccount a;
Bankaccount b;
a.accnumber = 123456;
a.accbalance =50;
b.accnumber = 67890;
b.accbalance = 2000;
std::cout<<"Account details of A\n\n";
a.display(); // this is how to use display
std::cout<<"\nAccount details of B\n\n";
b.display();
return 0;
}
You are inserting to std::cout, among others, result returned from function display
which should be int, but, considering that your function has no return statement everything is possible, basically you are sending undefined value to ostream cout, and that is what garbage is by definition.
Most probably this is what you wanted to achieve:
https://wandbox.org/permlink/bpPth9WutHaiU5jQ
#include <bits/stdc++.h>
using namespace std;
class Bankaccount {
public:
int accnumber, accbalance;
std::ostream& display(std::ostream& out) const
{
out << "Account number is: " << accnumber;
return out << "\nAccount balance is: " << accbalance;
}
};
std::ostream& operator<<(std::ostream& out, const Bankaccount& acc)
{
return acc.display(out);
}
int main()
{
Bankaccount a;
Bankaccount b;
a.accnumber = 123456;
a.accbalance = 50;
b.accnumber = 67890;
b.accbalance = 2000;
cout << "Account details of A\n" << a << endl;
cout << "\nAccount details of B\n" << b << endl;
return 0;
}
Your int display() function doesn't return an int so you'll have undefined behaviour after that function has been called. If it had returned an int, that number had been printed, but I suspect that's not what you wanted.
The garbage you see is an int picked from the stack (because display() was supposed to put an int there). It was put the for a reason by some other function, but now it's gone, so anything can happen. To avoid this, you could declare your function void display() - but then you wouldn't be able to stream it, which is what it looks like you want to do.
If you want to be able to stream your objects, you need to define streaming operators to do the job. I've replaced your display() function with an out stream operator (operator<<) here:
#include <iostream>
//#include<bits/stdc++.h> // non-portable, don't use it
// using namespace std; // brings in too much in the namespace
using std::cout; // prefer this or just write std::cout everywhere
class Bankaccount {
public:
int accnumber, accbalance;
friend std::ostream& operator<<(std::ostream& os, const Bankaccount& ba) {
return os << "Account number is : " << ba.accnumber
<< "\nAccount balance is: " << ba.accbalance << "\n";
}
};
int main() {
Bankaccount a;
Bankaccount b;
a.accnumber = 123456;
a.accbalance = 50;
b.accnumber = 67890;
b.accbalance = 2000;
// std::endl is approx. the same as "\n" + std::flush. You don't need flushing.
cout << "Account details of A\n\n" << a << "\n";
cout << "\nAccount details of B\n\n" << b << "\n";
}
This question already has answers here:
What's the difference between assignment operator and copy constructor?
(8 answers)
Closed 4 years ago.
I have this code:
the output of the code is:
cons intcons op+ intcons ;
copycons op+ intcons op+= ;
get_val 3
class declaration::
#include<iostream>
using namespace std;
class Int {
public:
// constructors
Int() : val_(0) { cout << "cons "; }
Int(int n) { val_ = n; cout << "intcons "; }
Int(const Int &v) : val_(v.val_) { cout << "copycons "; }
Int(Int &&v_) { val_ = v_.val_; cout << "mov ctor " ; };
// operations
int get_val() {
cout << "get_val "; return val_;
}
Int operator+(const Int &v) {
cout << "op+ ";
return Int(val_ + v.val_);
}
Int & operator=(const Int &v) {
cout << "op= ";
if (this != &v) {
val_ = v.val_;
}
return *this;
}
Int & operator+=(const Int &v) {
cout << "op+= ";
val_ += v.val_;
return *this;
}
private:
int val_; // value stored in this Int
};
and this is main:
int main(){
Int zero;
Int one = zero + 1;
cout << ";\n";
Int two = zero;
two += one + one;
cout << ";\n";
cout << two.get_val() + 1; cout << endl;
return 0;
}
I was looking at the codes output, and I could agree with each operation that happens and with every output. but one thing isn't clear to me at all. I wonder, why in the first line of the output there isn't use with the copy c'tor?
at first I though maybe it is a move c'tor.
then I built one and it doesn't seemed like the compiler was using it.
can anyone please tell me what is going on? thank you!
I think you are confusing the assignment operator with the copy constructor.
Int two = zero; will cause the copy constructor to be called.
two = zero or two = 1 will cause the assignment operator to be called.
https://techdifferences.com/difference-between-copy-constructor-and-assignment-operator.html
#include "assert.h"; // for some reason assert wouldn't work on my compiler without this
#include <iostream>
#include <string>
#include <limits> // This is helpful for inputting values. Otherwise, funny stuff happens
using namespace std;
class Product
{
public:
Product();
Product(string the_name, int the_price, int number_of);
string return_name();
void reduce_amount();
void print_data() const;
private:
string prod_name; // name of your product
int price_in_cents; // it's price in cents
int amount; // the number of the product that you have
};
Product::Product()
{
prod_name = "NULL_NAME: NEED DATA";
price_in_cents = 0;
}
Product::Product(string the_name, int the_price, int number_of)
{
assert(the_price>0);
assert(number_of>0);
assert(number_of<21);
assert(prod_name !="NULL_NAME: NEED DATA");
prod_name = the_name;
price_in_cents = the_price;
amount = number_of;
}
void Product::print_data() const
{
cout<<prod_name << endl;
cout<<"The price in cents is: " <<price_in_cents<< endl;
cout<< "Amount left: " << " " << amount << endl;
}
void Product::reduce_amount()
{
amount = amount -1;
}
string Product::return_name()
{
return prod_name;
}
class Vending_Machine
{
public:
Vending_Machine();
void empty_coins();
void print_vend_stats();
void add_product();
Product buy_product();
private:
int income_in_cents;
Product product1();
Product product2();
Product product3();
Product product4();
Product product5();
};
void Vending_Machine::empty_coins()
{
cout << "The total amount of money earned today is " << income_in_cents << " cents" << endl;
income_in_cents = 0;
cout << "All the coins have been withdrawn. The balance is now zero." << endl;
}
void Vending_Machine::print_vend_stats()
{
cout<< "Total income thus far: " << income_in_cents << endl;
if (product1().return_name() != "NULL_NAME: NEED DATA")
{
//stuff happens
}
}
int main()
{
return 0;
}
So, I'm not sure if I did all the identation correctly, but I'm having a problem with the boolean statement in vending machine print_vend_stats() function. It's saying I am making an undefined fereence to product1(). What does this mean?
When you declare
Product product1();
you declare a member function, the parentheses is what makes it a function.
If you drop the parentheses
Product product1;
you declare a member variable, an actual instance of the Product class.
Another example, you wouldn't write e.g.
int income_in_cents();
do declare income_in_cents as a variable, now would you?
It doesn't matter if the type is a primitive type like int, or a class like Product, Member variables are declared like normal variables like you do anywhere else.
I'm having some problems with my program which I do not understand.
On line 72, I get the error: "error C4700: uninitialized local variable 'sumInEuros' used" however surely it is initialized as I am using it to store a calculation?
Also on line 66 I get "error C4716: 'showPriceInEuros': must return a value" - why must this return a value? the function is simply meant to output a message to the console.
I'm using VS13 and it's c++.
Any help would be very much appreciated, because I am stuck!
Thanks!
#include <iostream> //for cin >> and cout <<
#include <cassert> //for assert
#include <iomanip> //for endl
#include <Windows.h>
using namespace std;
void processAPrice();
int getPriceInPounds();
int convertPriceIntoEuros(int pounds);
int showPriceInEuros(int pounds, int euros);
int calculateSum(int euros);
void produceFinalData(int sum, int numberOfPrices);
int main()
{
char answer('Y');
int numberOfPrices(0);
while (answer = 'Y')
{
processAPrice();
numberOfPrices++;
cout << "Continue? (Y/N)";
cin >> answer;
}
if (numberOfPrices > 0)
//produceFinalData(sum, numberOfPrices);
system("PAUSE"); //hold the screen until a key is pressed
return(0);
}
void processAPrice() //
{
int pounds = getPriceInPounds();
int euros = convertPriceIntoEuros(pounds);
int sum = showPriceInEuros(pounds, euros);
calculateSum(euros);
}
int getPriceInPounds() //
{
int priceInPounds;
cout << "Enter a price (in Pounds): /234";
cin >> priceInPounds;
return priceInPounds;
}
int convertPriceIntoEuros(int priceInPounds) //
{
const int conversionRate(0.82);
return priceInPounds / conversionRate;
}
int showPriceInEuros(int pounds, int euros) //
{
SetConsoleOutputCP(1252);
cout << "The Euro value of /234" << pounds << "is: \u20AC" << euros;
}
int calculateSum(int euros) //
{
int sumInEuros;
sumInEuros = (sumInEuros + euros);
return sumInEuros;
}
void produceFinalData(int sum, int numberOfPrices) //
{
SetConsoleOutputCP(1252);
cout << "The total sum is: \u20AC" << sum;
cout << "The average is: \u20AC" << (sum/numberOfPrices);
}
Well, the showPriceInEuros function is not returning the int it promises to return in its signature. That's the error.
If the function is not supposed to return a value, you should declare its return type as void:
void showPriceInEuros(int pounds, int euros);
//^^
and then:
void showPriceInEuros(int pounds, int euros) {
SetConsoleOutputCP(1252);
cout << "The Euro value of /234" << pounds << "is: \u20AC" << euros;
}
of course.
surely it is initialized as I am using it to store a calculation?
The calculation is based on the variable's uninitialised value:
sumInEuros = (sumInEuros + euros);
^^^^^^^^^^ not initialised
Perhaps you could declare it static, so that its value is preserved between calls to the function, in order to calculate the sum of all the values you pass to the function. Usually, it would be better to use a class to manage persistent data like this, with member functions to update and access it.
why must this return a value?
Because you say it does:
int showPriceInEuros(int pounds, int euros)
^^^
If it shouldn't return a value, change the return type to void.
You do not initialize sumInEuros in this function. You store a result in it - that's true but to calculate the result you are using the uninitialized value.
int calculateSum(int euros) //
{
int sumInEuros;
sumInEuros = (sumInEuros + euros);
return sumInEuros;
}
Answering the question from below:
I would probably create a class PriceCalculator which has all the functions of your algorithm plus the internal state:
class PriceCalculator {
int m_sumInEuros;
public:
PriceCalculator()
: m_sumInEuros(0) { }
void processAPrice(int price);
int getSumInEuros() const { return m_sumInEuros; }
private:
void updateSum(int priceInEuros);
};
From your main function you should create an object of this type and give it the prices you want to sum. Do not do any console input from your class.
int main()
{
PriceCalculator calc;
char answer('Y');
int numberOfPrices(0);
while (answer = 'Y')
{
int priceInPounds;
cout << "Enter a price (in Pounds): /234";
cin >> priceInPounds;
calc.processAPrice(priceInPounds);
numberOfPrices++;
cout << "Continue? (Y/N)";
cin >> answer;
}
...
You might want to think about adding the numberOfPrices to your calculator class as well. At the end you will do all the operations in your class but the user input and console output outside your class. Your class can be tested automatically this way and is completely independent from the user interface.