简体   繁体   English

未在此类范围C中声明变量

[英]Variable was not declared in this class scope C++

I want to create class moneybox, that accepts adding to the sum coints with value 1,5 and 10 cents. 我想创建一个类别的扑满,它接受将值1,5和10美分添加到总币中。

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 45:15:错误:未在此范围内声明'five_num'47:10:错误:未在此范围内声明'ones'47:20:错误:未在此范围内声明'tens'48:10:错误:未在此范围内声明“ fives”

Why it happends and how to fix it? 为什么会发生以及如何解决?

You can't pass parameters by name in C++. 在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. 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 C ++是一种非常强大的语言,通过一些巧妙的编码,您可以有效地支持命名参数来启用诸如

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. Boost(www.boost.org)相当使用此样式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM