C ++类和范围问题

时间:2016-02-27 01:56:01

标签: c++ class scope

#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;
}

我试图获得该部分:

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

实际打印出手机和传真号码,但它只给我随机数字。如果我将手机和传真显示屏移到他们创作的下方,它就可以工作,但不在这里。发生了什么,我该如何解决?

1 个答案:

答案 0 :(得分: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(...){