无法弄清楚为什么头文件中的私有成员无法在cpp文件中工作

时间:2011-10-26 22:41:41

标签: c++ header private member

您好我一直在寻找修复此问题的地方,并尝试了多种不同的方法来定义.cpp文件中的ListNode。由于某种原因,结构不能与.cpp文件共享。任何帮助将非常感激。 谢谢

.H文件:

#ifndef SORTEDLIST_H
#define SORTEDLIST_H

#include "Student.h"

/*
 * SortedList class
 *
 * A SortedList is an ordered collection of Students.  The Students are ordered
 * from lowest numbered student ID to highest numbered student ID.
 */
class SortedList {

  public:

    SortedList();
    // Constructs an empty list.

bool insert(Student *s);
// If a student with the same ID is not already in the list, inserts 
// the given student into the list in the appropriate place and returns
// true.  If there is already a student in the list with the same ID
// then the list is not changed and false is returned.

Student *find(int studentID);
// Searches the list for a student with the given student ID.  If the
// student is found, it is returned; if it is not found, NULL is returned.

Student *remove(int studentID);
// Searches the list for a student with the given student ID.  If the 
// student is found, the student is removed from the list and returned;
// if no student is found with the given ID, NULL is returned.
// Note that the Student is NOT deleted - it is returned - however,
// the removed list node should be deleted.

void print() const;
// Prints out the list of students to standard output.  The students are
// printed in order of student ID (from smallest to largest), one per line

private:

// Since ListNodes will only be used within the SortedList class,
// we make it private.
struct ListNode {    
  Student *student;
  ListNode *next;
};

ListNode *head; // pointer to first node in the list
};

#endif

.CPP文件:

#include <iostream>
#include "SortedList.h"

using namespace std;


SortedList::SortedList() : head(NULL){}



Student SortedList::*find(int studentID){
ListNode *current;
current = head;
if(current != NULL){
 while(current != NULL){
               if(current.student.getID() == studentID){
               return current.student;
               }
 current = current.next;
 }
}
return NULL;                   
}

相关错误:      C:\ Users \ Charles \ Desktop \ SortedList.cpp函数Student SortedList::* find(int)': 12 C:\Users\Charles\Desktop\SortedList.cpp ListNode'未声明(首次使用此函数)

3 个答案:

答案 0 :(得分:2)

这一行错了:

Student SortedList::*find(int studentID) {

你把明星放在了错误的地方。这是{em>不 SortedList::find定义的前导码,返回Student*。这是名为find自由函数定义的序言,它返回Student SortedList::*。 (一种不寻常但形式良好的“指向成员的指针”类型)。因为它不是SortedList成员方法,所以SortedList的内部声明都不在范围内,这就是你得到那个令人困惑的错误信息的原因。

这是你应该写的:

Student *
SortedList::find(int studentID)
{

(将其分成三行是没有必要的,但会让其他人更容易阅读您的代码。)

答案 1 :(得分:1)

你得到的编译错误有点误导;您的问题根本与ListNode无关。你的cpp文件中有语法错误:

Student *SortedList::find(int studentID)

这意味着SortedList::find会返回指向学生的指针。

答案 2 :(得分:0)

正确的签名是:

Student* SortedList::find(int studentID)

指针是返回类型的一部分,不是方法名称的一部分。