Синтаксические ошибки с прокси: что я делаю не так? - PullRequest
0 голосов
/ 31 октября 2011

В настоящее время я изучаю C ++ в своей книге, и у них было упражнение по использованию ранее созданного класса IntList и его реализации с использованием IntListProxy.Моя книга говорит только о прокси в очень простом примере, поэтому мне сложно разобраться с его синтаксисом.Что я делаю не так с этим прокси и как я могу это исправить?Имейте в виду, что IntList уже является .o, и мне не разрешается включать IntList.cpp при компиляции.Ошибка:

IntListProxy.cpp: In member function ‘bool IntListProxy::isEmpty()’:
IntListProxy.cpp:7: error: invalid use of incomplete type ‘struct IntList’
IntListProxy.h:5: error: forward declaration of ‘struct IntList’
IntListProxy.cpp: In member function ‘IntListProxy* IntListProxy::prepend(int)’:
IntListProxy.cpp:13: error: invalid use of incomplete type ‘struct IntList’
IntListProxy.h:5: error: forward declaration of ‘struct IntList’
IntListProxy.cpp: In member function ‘int IntListProxy::head()’:
IntListProxy.cpp:19: error: invalid use of incomplete type ‘struct IntList’
IntListProxy.h:5: error: forward declaration of ‘struct IntList’
IntListProxy.cpp: In member function ‘IntListProxy* IntListProxy::tail()’:
IntListProxy.cpp:25: error: invalid use of incomplete type ‘struct IntList’
IntListProxy.h:5: error: forward declaration of ‘struct IntList’
IntListProxy.cpp: In member function ‘std::string IntListProxy::toString()’:
IntListProxy.cpp:31: error: invalid use of incomplete type ‘struct IntList’
IntListProxy.h:5: error: forward declaration of ‘struct IntList’
IntListProxy.cpp: In member function ‘int IntListProxy::length()’:
IntListProxy.cpp:37: error: invalid use of incomplete type ‘struct IntList’
IntListProxy.h:5: error: forward declaration of ‘struct IntList’
IntListProxy.cpp: In member function ‘IntListProxy*       `IntListProxy::append(IntListProxy*)’:`
IntListProxy.cpp:43: error: invalid use of incomplete type ‘struct IntList’
IntListProxy.h:5: error: forward declaration of ‘struct IntList’
IntListProxy.cpp: In member function ‘int IntListProxy::operator[](int)’:
IntListProxy.cpp:49: error: invalid use of incomplete type ‘struct IntList’
IntListProxy.h:5: error: forward declaration of ‘struct IntList’
IntListProxy.cpp:51: error: expected unqualified-id before ‘}’ token
IntListProxy.cpp:51: error: expected ‘;’ before ‘}’ token

IntListProxy.h

#include <iostream>
#include <string>

using namespace std;
class IntList;

class IntListProxy
{
 public:
  IntListProxy();
  bool isEmpty();
  IntListProxy *prepend(int n);
  int head();
  IntListProxy *tail();
  string toString();
  int length();
  IntListProxy *append(IntListProxy *lst);
  int operator[](int n);
 private:
  IntList *ptr;

};

IntListProxy.cpp

#include "IntListProxy.h"

IntListProxy::IntListProxy(){}

bool IntListProxy::isEmpty(){

  ptr->isEmpty();

}

IntListProxy *IntListProxy::prepend(int n){

  return ptr->prepend(n);

}

int IntListProxy::head(){

  return ptr->head();

}

IntListProxy *IntListProxy::tail(){

  return ptr->tail();

}

string IntListProxy::toString(){

  return ptr->toString();

}

int IntListProxy::length(){

  return ptr->length();

}

IntListProxy *IntListProxy::append(IntListProxy *lst){

  return ptr->append(lst);

}

int IntListProxy::operator[](int n){

  return ptr->operator[](n);

}

Заранее спасибо!

Ответы [ 3 ]

2 голосов
/ 31 октября 2011

Предлагаемое решение:
Вам необходимо включить заголовочный файл, который определяет класс IntList, в ваш файл cpp IntListProxy.cpp.

Объяснение:
Когда вместо включения заголовочного файла вы добавляете строку:

class IntList;

В программе Forward объявляется класс IntList, что означает для компилятора, что это Неполный тип .С незавершенными типами, Нельзя создавать объекты этого или делать что-либо, что требует компилятору знать расположение IntList или больше, чем тот факт, что IntList является просто типом.То есть: компилятор не знает, каковы его члены и какова его структура памяти.Но поскольку указатели на все объекты требуют одинакового распределения памяти, вы можете использовать прямое объявление, когда просто ссылаетесь на незавершенный тип в качестве указателя.

В этом случае ваш файл cpp IntListProxy.cpp должен знать макет(члены) IntList, чтобы иметь возможность разыменовать его и, следовательно, ошибку.

0 голосов
/ 31 октября 2011

Вы только что объявили IntList.Компилятор не знает, какие методы существуют в этом struct.Следовательно, вам нужно включить заголовочный файл, содержащий определение IntList в прокси-файл cpp.

0 голосов
/ 31 октября 2011

В строке 7, где вы звоните isEmpty, IntList только объявлено заранееКомпилятор еще не видел фактическое определение класса.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...