在C ++

时间:2017-05-07 10:03:03

标签: c++

我一直在寻找各处,但我找不到解决方案,虽然它可能很简单,因为我刚刚开始。基本上,我试图通过构造函数传递两个值,但是我传入的值在运行或调试时都不正确。

Transaction.h

#include <string>

class Transaction {
  private:
    int amount;
    std::string type; 

  public:
    Transaction(int amt, std::string kind);
    std::string Report() const;

    // ...irrelevant code...
};

Transaction.cpp

#include "Transaction.h"
using namespace std;

Transaction::Transaction(int amt, std::string kind) { };

string Transaction::Report() const {
  string report;
  report += " ";
  report += type;  // supposed to concat "Deposit" to string
  report += " ";
  report += to_string(amount);  // supposed to concat amount to string

  return report;
  // This doesn't return the word "Deposit", nor does
  // it return the correct amount. I don't think that
  // this is adding "Deposit" to 50, because the values
  // change every time I run the program.
}

Parameters.cpp

#include "Transaction.h"
#include <iostream>
using namespace std;

// ...irrelevant code...

int main() {

  int money = 50;
  cout << "Depositing $" << money << endl;

  Transaction deposit(money, "Deposit");  
  // For some reason, this doesn't pass in int money.

  cout << "Original: " << deposit.Report() << endl;
  // And this cout prints some large value instead of 50.

  // ...irrelevant code...
}

无论我做什么,价值都会发生变化。我得到了一些输出:

Depositing $50
Original:   13961048
After pass by value:   13961048
After pass by reference:   27922096

Depositing $50
Original:   11208536
After pass by value:   11208536
After pass by reference:   22417072

Depositing $50
Original:   14092120
After pass by value:   14092120
After pass by reference:   28184240

任何指导我正确方向的帮助(或者只是一个正确的答案)都会很棒!

2 个答案:

答案 0 :(得分:9)

传递到构造函数,好吧。问题只是你没有用它们做任何事情!

查看构造函数的实现:

Transaction::Transaction(int amt, std::string kind) { };

这没有任何作用。特别是,它不会保存(存储)传递的参数值。

你可能想要这个:

Transaction::Transaction(int amt, std::string kind)
   : amount(amt)
   , type(kind)
{ }

奇怪的冒号语法称为member initialization list,并且听起来就是这样。

请注意, 应该能够在调试器中看到这一点。你要做的是在构造函数的定义上设置一个断点,然后检查参数的值是什么。你会看到它们被正确传递(并且值不是“错误的”)。然后你必须弄清楚为什么他们没有得到保存,你可以通过从那一点单步执行代码来很容易地看到它。

答案 1 :(得分:-1)

您不会将副本的值传递给类变量

这里是正确的构造函数代码:

Transaction::Transaction(int amt, std::string kind) { 
      this->amount=amt; //copy the value of amt to Transaction.amount
      this->type=kind;  //copy the value of kind to Transaction.kind

};