我一直在到处搜索,但我找不到解决方案,尽管它可能是一个简单的解决方案,因为我刚刚开始。基本上,我试图通过构造函数传入两个值,但我传入的值在运行或调试时都不正确。
事务.h
#include <string>
class Transaction {
private:
int amount;
std::string type;
public:
Transaction(int amt, std::string kind);
std::string Report() const;
// ...irrelevant code...
};
事务.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.
}
参数.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...
}
无论我做什么,值(value)都会改变。我得到的一些输出:
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
任何帮助我指明正确方向(或直接回答)的人都会很棒!
最佳答案
值正在传递给构造函数,好的。问题是您没有对它们做任何事情!
查看构造函数的实现:
Transaction::Transaction(int amt, std::string kind) { };
这没有做任何事情。特别是,它不会保存(存储)传递的参数值。
你可能想要这个:
Transaction::Transaction(int amt, std::string kind)
: amount(amt)
, type(kind)
{ }
奇怪的冒号语法被称为 member initialization list , 并如其所愿。
请注意,您应该已经能够在调试器中看到它。您要做的是在构造函数的定义上设置一个断点,然后检查参数的值是什么。您会看到它们被正确传递(并且值不是“错误的”)。然后你必须弄清楚为什么他们没有被保存,你可以通过从那时起单步执行代码很容易地看到这一点。
关于c++ - 在 C++ 中将错误的值传递给构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43830169/