2016-02-27 61 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