如何访问另一个类中的一个类的成员函数? [英] How to access member function of one class inside another class?

查看:255
本文介绍了如何访问另一个类中的一个类的成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法访问另一个类中的一个类的成员函数,虽然我可以访问它在main()。我一直在试图切换的东西,但无法理解我做错了什么。

I am unable to access a member function of one class inside another, though I can access it fine in main(). I've been trying to switch things around, but am unable to understand what am I doing wrong. Any help would be appreciated.

以下是产生错误的行:

cout << "\n\nRetrieve key from inside Envelope class: " << e.getData() << "\n\n";

这里是代码:

class Record{
  private:
    string key;
  public:
    Record(){ key = ""; }
    Record(string input){ key = input; }
    string getData(){ return key; }
    Record operator= (string input) { key = input; }
};

template<class recClass>
class Envelope{
  private:
    recClass * data;
    int size;

  public:
    Envelope(int inputSize){
      data = new recClass[inputSize];
      size = 0;
    }
    ~Envelope(){ delete[] data; }
    void insert(const recClass& e){
      data[size] = e;
      cout << "\n\nRetrieve key from inside Envelope class: " << e.getData() << "\n\n";
      ++size;
    }
    string getRecordData(int index){ return data[index].getData(); }
};

int main(){

  Record newRecord("test");
  cout << "\n\nRetrieve key directly from Record class: " << newRecord.getData() << "\n\n";

  Envelope<Record> * newEnvelope = new Envelope<Record>(5);
  newEnvelope->insert(newRecord);
  cout << "\n\nRetrieve key through Envelope class: " << newEnvelope->getRecordData(0) << "\n\n";

  delete newEnvelope;
  cout << "\n\n";
  return 0;
}


推荐答案

$ c> e 作为常量引用 void insert(const recClass& e){

然后你调用方法( getData())未声明为常数。

You are passing e as a constant reference void insert(const recClass& e){
And then you are calling a method (getData()) not declared as constant.

您可以通过重写 getData()就像这样:

You can fix it by rewriting getData() like this:

string getData() const{ return key; }

这篇关于如何访问另一个类中的一个类的成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆