我一直在尋找無處不在,但我找不到解決方案,但它可能是一個簡單的,因爲我剛剛開始。基本上,我試圖通過構造函數傳入兩個值,但傳入的值在運行或調試時都不正確。錯誤的值被傳遞給構造函數在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
任何幫助指向我在正確的方向(或只是一個直接的答案)將是偉大的!
你太了不起了。感謝你!就像跟進一樣,我的程序從哪裏抓取數字?無論記憶中有什麼? – MylesWritesCode
取決於正在初始化的類型。構造對象時,非基元類型的成員變量的默認構造函數被調用,除非另有初始化。在'std :: string'的情況下,這會產生空字符串。對於'int'原始類型,該值是未定義的,因此編譯器可以在該位置放置任何喜歡的值。 –
謝謝你的澄清! – MylesWritesCode