2016-02-27 142 views
-2
#include<iostream> 
using namespace std; 

// Contact.h 
class Contact 
{ 
public: 
    Contact(); 
    Contact(int, int, int); 
    void display(); 
private: 
    int left; 
    int middle; 
    int right; 
}; 

//Bank.h 
class Bank // Bank class definition 
{ 
    public: 
    Bank(); 
    Bank(int bank_ID, Contact phone, Contact fax); 
    void display(); 
    private: 
    int bank_ID; // 4 digit integer 
    Contact phone; // object three integer pieces: ###, ###, #### 
    Contact fax; // object three integer pieces, ###, ###, #### 
}; 

// Loan.h 
class Loan 
{ 
    public: 
    Loan(Bank bank, ID id); 
    void display(); 
    private: 
    Bank bank; 
}; 

Bank::Bank(){ 

} 

Bank::Bank(int bankID, Contact phoneIN, Contact faxIN){ 
    bank_ID = bankID; 
    Contact phone(555, 555, 555); 
    Contact fax(111, 222, 3333); 

    cout << "Works here\n"; 
    phone.display(); 
    fax.display(); 
} 

void Bank::display() 
{ 
    cout << "Bank: " << bank_ID << endl; 
    cout << "Doesn't work here :(\n"; 
    phone.display(); 
    fax.display(); 
} 

Contact::Contact() 
{ 
} 

Contact::Contact(int l, int m, int r) 
{ 
    left = l; 
    middle = m; 
    right = r; 
} 

void Contact::display() 
{ 
    cout << "Number: " << left << "-" << middle << "-" << right << endl; 
} 

Loan::Loan(Bank bankID) 
{ 
    bank = bankID; 
} 

void Loan::display() 
{ 
    bank.display(); 
} 

int main() 
{ 
    Loan loan1(Bank(1234, Contact(), Contact())); 
    cout << "Display loan1 \n"; 
    loan1.display(); 
    return 0; 
} 

我試圖讓部分:C++類和範圍問題

void Bank::display() 
{ 
    cout << "Bank: " << bank_ID << endl; 
    phone.display(); 
    fax.display(); 
} 

實際打印出電話和傳真號碼,但它只是讓我的隨機數。如果我將手機和傳真顯示器移動到其創建的位置以下,但它不在此處,它將起作用。怎麼回事,我該如何解決?

+0

請提供所有代碼neccessary明白你的問題不遵循外部鏈接。 – Anedar

+0

stackoverflow.com問題必須是完整的問題,而不是其他網站的鏈接。請發佈一個完整的問題。 –

+1

更好的是,儘量減少你的代碼到http://stackoverflow.com/help/mcve – aschepler

回答

2

,可能會導致您的問題問題是這樣的:

Bank::Bank(int bankID, Contact phoneIN, Contact faxIN){ 
    bank_ID = bankID; 
    Contact phone(555, 555, 555); 
    Contact fax(111, 222, 3333); 

    cout << "Works here\n"; 
    phone.display(); 
    fax.display(); 
} 

在這裏,你創建局部變量稱爲phonefax,你不使用你的類成員。

對於使用類成員,無論是寫

phone = Contact (...); 

,或者使用一個成員初始化列表如下:

Bank::Bank(int bankID, Contact phoneIN, Contact faxIN):phone(...){ 
+0

謝謝你的解釋。我的印象是,聯繫人的電話和傳真可以在世行任何地方使用,因爲他們在世行的申報表中。 – Chirality