2017-05-07 91 views
1

我一直在尋找無處不在,但我找不到解決方案,但它可能是一個簡單的,因爲我剛剛開始。基本上,我試圖通過構造函數傳入兩個值,但傳入的值在運行或調試時都不正確。錯誤的值被傳遞給構造函數在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 

任何幫助指向我在正確的方向(或只是一個直接的答案)將是偉大的!

回答

9

這些值是通過給構造函數,好吧。問題在於你不是正在做什麼與他們!

看看在構造函數的實現:

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

這並不做任何事情。特別是,它不會保存(存儲)傳遞參數的值。

你可能想這樣的:

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

怪異的冒號語法被稱爲member initialization list,並且不只是這聽起來像。

請注意,你應該已經能夠在調試器中看到這一點。你要做的是在構造函數的定義上設置一個斷點,然後檢查參數的值。你會發現它們被正確地傳遞(並且值不是「錯誤的」)。然後,你必須弄清楚爲什麼他們沒有得到保存,而且你可以很容易地通過單步執行代碼來看到這一點。

+0

你太了不起了。感謝你!就像跟進一樣,我的程序從哪裏抓取數字?無論記憶中有什麼? – MylesWritesCode

+1

取決於正在初始化的類型。構造對象時,非基元類型的成員變量的默認構造函數被調用,除非另有初始化。在'std :: string'的情況下,這會產生空字符串。對於'int'原始類型,該值是未定義的,因此編譯器可以在該位置放置任何喜歡的值。 –

+0

謝謝你的澄清! – MylesWritesCode

-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 

}; 
+0

爲什麼使用'this'? – 2017-05-07 10:12:52

+0

這裏沒有必要。是我的習慣,因爲我用來調用具有相同名稱的變量,爲此我用它來指定類變量的類。 –

+1

這個。不會編譯。這是一個指針。 – 2017-05-07 10:19:05

相關問題