2

我无法在另一个类中访问一个类的成员函数,尽管我可以在 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;
}
4

2 回答 2

6

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

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

string getData() const{ return key; }
于 2013-02-08T01:47:45.837 回答
5

您必须声明它可以从上下文getData()中调用。你的函数需要 a所以你想这样做:constconstinsertconst recClass& eRecord

string getData() const { return key; }
于 2013-02-08T01:48:20.900 回答