繁体   English   中英

如何在另一个类中访问一个类的成员函数?

[英]How to access member function of one class inside another class?

我无法在另一个类中访问一个类的成员函数,尽管我可以在main()中访问它。 我一直试图改变现状,但我无法理解我做错了什么。 任何帮助,将不胜感激。

以下是生成错误的行:

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

您将e作为常量引用传递void insert(const recClass& e){
然后你调用一个未声明为常量的方法( getData() )。

您可以通过重写getData()来修复它:

string getData() const{ return key; }

您必须将getData()声明为const以便可以从const上下文中调用它。 你的insert函数采用const recClass& e所以你想在Record执行此操作:

string getData() const { return key; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM