错误预期在'之前的主要表达 - '代币

时间:2016-02-20 20:45:43

标签: c++ function class struct

所以我在这个名为Money的结构中有结构代码:

class Money{
  private:
    unsigned int numDollars;    // number of dollars
    unsigned int numQuarters;   // number of quarters (25 cents)
    unsigned int numDimes;      // number of dimes (10 cents)
    unsigned int numNickels;    // number of nickels (5 cents)
    unsigned int numPennies;    // number of pennies (1 cents)

  public:
 // constructors for the class
 // Exercise 1 is to implement these
     Money();
     Money(unsigned int dollars, unsigned int cents);
     Money(unsigned int dd, unsigned int q, unsigned int d, unsigned int n, unsigned int p);

 // getter functions
 // these are provided for you
     unsigned int getDollars();
     unsigned int getQuarters();
     unsigned int getDimes();
     unsigned int getNickels();
     unsigned int getPennies();

 // you need to implement this getter in Exercise 2
     unsigned int getCents();

 // setter functions
 // you need to implement each of these in Exercise 2
     void addMoney(Money);
     void addDollars(unsigned int);
     void addQuarters(unsigned int);
     void addDimes(unsigned int);
     void addNickels(unsigned int);
     void addPennies(unsigned int);
     void addCents(unsigned int);

 // other methods for Exercise 3
 void leastCoins();               // Exercise 3
 unsigned int numberOfCoins();    // Exercise 3

};

所以给我错误的代码是我定义我的void addMoney()函数时。它应该像这样工作:如果我说m1.addMoney(m2)m1应该+= m2,而m2保持不变。 我试图简单地将m2的硬币添加到m1

void Money::addMoney(Money)
{
    Money::addDollars(Money.getDollars);
    Money::addQuarters(Money.getQuarters());
    Money::addDimes(Money.getDimes());
    Money::addNickels(Money.getNickels());
    Money::addPennies(Money.getPennies());
}

此处的所有行都会引发该错误。

1 个答案:

答案 0 :(得分:1)

你的功能看起来像这样

void Money::addMoney(Money const& other)
{
    addDollars(other.getDollars());
    addQuarters(other.getQuarters());
    addDimes(other.getDimes());
    addNickels(other.getNickels());
    addPennies(other.getPennies());
}

您实际上是隐式地从this调用每个方法,这是指向Money的当前实例的指针。然后,您可以从get_调用other,这是作为参数传入的另一个Money