【问题标题】:C++ Class and Scope IssueC++ 类和范围问题
【发布时间】:2016-02-27 01:56:00
【问题描述】:
#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();
}

实际打印出电话和传真号码,但它只是给我随机数字。如果我将电话和传真显示移到它们的创建下方,它会起作用,但不会在这里。发生了什么,我该如何解决?

【问题讨论】:

  • 请提供所有必要的代码来理解您的问题,而无需关注外部链接。
  • stackoverflow.com 问题必须是完整的问题,而不是指向其他网站的链接。请发布一个完整的问题。
  • 更好的是,尝试将您的代码缩减为stackoverflow.com/help/mcve
  • 更新帖子。我尽量把它修剪下来。
  • @Revolt 是时候启动调试器并逐步执行代码了。

标签: c++ class scope


【解决方案1】:

可能导致您的问题的问题是:

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(...){

【讨论】:

  • 感谢您的解释。我的印象是联系电话和传真可以在 Bank 的任何地方使用,因为它们是在 Bank 类中声明的。
猜你喜欢
  • 2022-01-21
  • 2011-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 2014-12-28
  • 2015-01-30
  • 1970-01-01
相关资源
最近更新 更多