I want to create class moneybox, that accepts adding to the sum coints with value 1,5 and 10 cents.
Here is my code:
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
using namespace std;
class MoneyBox{
public:
MoneyBox(int one_num = 0 ,int five_num = 0,int ten_num = 0);
void print();
MoneyBox add(int ones,int fives,int tens);
private:
int sum;
int one_num;
int five_num;
int ten_num;
};
MoneyBox::MoneyBox(int ones,int fives,int tens){
sum = 1*ones + 5*fives + 10*tens;
one_num = ones;
five_num = fives;
ten_num = tens;
}
void MoneyBox::print(){
cout << one_num <<"*"<<"1Cent" << five_num <<"*"<<"5Cent" << ten_num <<"*"<<"10Cent" << "=" << sum;
}
MoneyBox MoneyBox::add(int ones,int fives,int tens){
one_num += ones;
five_num += fives;
ten_num += tens;
sum += 1 * ones + 5 * fives + 10*tens;
return MoneyBox(one_num,five_num,ten_num);
}
int main(){
MoneyBox m_1;
MoneyBox m_2(five_num = 3);
m_1.add(ones = 4, tens = 3);
m_2.add(fives = 3, ones = 2);
m_1.print();
cout << "\n";
m_2.print();
}
But compiler throws me an error:
45:15: error: 'five_num' was not declared in this scope 47:10: error: 'ones' was not declared in this scope 47:20: error: 'tens' was not declared in this scope 48:10: error: 'fives' was not declared in this scope
Why it happends and how to fix it?
You can't pass parameters by name in C++.
MoneyBox m_2(five_num = 3);
needs to be written as
MoneyBox m_2(0/*required to pass explicitly*/, 3);
and so on. five_num
&c. are not declared at the calling site, hence the compiler diagnostic. C++ is a very powerful language, and with some clever coding you could effectively support named parameters to enable calling syntax such as
MoneyBox(Five(5), One(2), /*any number of parameters in any order*.)
using variadic templates . Boost (www.boost.org) use this style a fair bit.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.