名称空间错误

Error with namespaces

本文关键字:错误 空间      更新时间:2023-10-16

嗨,我正在做一个作业,在课堂上熟悉使用名称空间。我得到了一些不同的错误,虽然我不知道为什么,因为我已经在其他4个头和。cpp文件w/o错误做了同样的过程,所以我被难住了。错误如下:

WriteFile.cpp: In function 'void WriteLine(CSC2100::WriteFile*, CSC2100::String*)':
WriteFile.cpp:39:27: error: invalid use of incomplete type 'struct CSC2100::String'
In file included from WriteFile.h:4:0,
                 from WriteFile.cpp:1;
String.h:6:11: error: forward declaration of 'struct CSC2100::String'
WriteFile.cpp:41:30: error: invalid use of incomplete type 'struct CSC2100::String'
In file included from WriteFile.h:4:0,
                 from Writefile.cpp:1:
String.h:6:11: error: forward declaration of 'struct CSC 2100::String'

我已经彻底检查了错误中提到的代码,但似乎找不到问题。我在WriteFile.cpp的顶部包含了前向声明以及错误所在的函数:

#include "WriteFile.h"
namespace CSC2100
{
   struct WriteFile
   {
      ofstream output_file;
      bool closed;
   };
}
#include <sstream>
using namespace CSC2100;
///////////////////////////////////////////
void writeLine(WriteFile* wf, String* line)
{
   if (!wf->closed && line->sz > 0)
   {
      wf->output_file << line->text << endl;
   }
}

这里是WriteFile.h:

#include "String.h"
#include <fstream>
using namespace std;
namespace CSC2100
{
   struct WriteFile;
}
CSC2100::WriteFile* createWriteFile(const char* file_name);
void destroyWriteFile(CSC2100::WriteFile* wf);
void writeLine(CSC2100::WriteFile* wf, CSC2100::String* line);
void close(CSC2100::WriteFile* wf);

我将继续包括错误中提到的String.h。String.cpp:

中结构体的前向声明
namespace CSC2100
{
   struct String
   {
      const char* text;
      int sz; 
   };
}

和String.h:

#if !defined STRING_STRUCT
#define STRING_STRUCT
namespace CSC2100
{
   struct String;
}
CSC2100::String* createString(const char* char_array);
void displayString(CSC2100::String* str);
void destroyString(CSC2100::String* str);
int length(CSC2100::String* str);
const char* getText(CSC2100::String* str);
int a_to_i(CSC2100::String* str);
float a_to_f(CSC2100::String* str);
CSC2100::String* i_to_a(int number);
CSC2100::String* f_to_a(float number);
int find(CSC2100::String* str, char delimiter, int start);
CSC2100::String* substr(CSC2100::String* str, int start, int end);
int compare(CSC2100::String* str1, CSC2100::String* str2);

代码应该和教授写的一样正确。我们所做的就是给它应用一个名称空间。

此代码

namespace CSC2100 {
   struct String {
       const char* text;
       int sz; 
   };
}

当然应该转到String.h而不是String.cpp !!

子>

<参见:包括. cpp文件

对于WriteFile.h,尝试(不包括String.h):

 #include <fstream>
 // #include "String.h" **** OMIT THIS ****
 namespace CSC2100 {
     class String;
 }
 // ...

并在WriteFile.cpp中包含String.h !

必须使用前向声明类声明(无论它们是否在特定的命名空间中)来解析这种循环引用。