C++ 两个类与一个(C+;+;)一起工作

C++ 两个类与一个(C+;+;)一起工作,c++,C++,我有三门课:扫描器、桌子、阅读器。扫描仪将信息添加到表中,读取器从表中读取信息。那么,我应该在哪里声明表变量呢?我在.h中做了,但有一个错误,即双重包含 可能是这样的: // Scanner.h #ifndef _Scanner_h_ // guard: ensure only one definition #define _Scanner_h_ #include "Table.h" class Scanner { .... void add(Table & tab

我有三门课:扫描器、桌子、阅读器。扫描仪将信息添加到表中,读取器从表中读取信息。那么,我应该在哪里声明表变量呢?我在.h中做了,但有一个错误,即双重包含

可能是这样的:

// Scanner.h
#ifndef _Scanner_h_  // guard: ensure only one definition
#define _Scanner_h_

#include "Table.h"

class Scanner
{
    ....
    void add(Table & table);   // implemented in Scanner.cpp
};

#endif

// Reader.h
#ifndef _Reader_h_
#define _Reader_h_

#include "Table.h"

class Reader
{
    ...
    void read(const Table & table);  // implemented in Reader.cpp
};

#endif

// Table.h
#ifndef _Table_h_
#define _Table_h_

class Table
{
    ...
};

#endif
大体上:

#include "Table.h"
#include "Scanner.h"
#include "Reader.h"

....
int main(int argc, char **argv)
{   
    Table table;
    Scanner scanner;
    Reader reader

    scanner.add(table);
    ....
    reader.read(table);
    ....
}

听起来你对多重定义有问题。 在每个页眉的顶部使用,并在页眉和页脚中包括每个C++类。

#pragma once
class Name {}
//or
#ifndef __CLASS_NAME_H__
#define __CLASS_NAME_H__
class Name { }
#endif
i、 e


“双重包含错误”向我暗示,单个文件在单个翻译单元中被多次包含。例如,假设您有:

表h 阅读器.h main.cpp 编译
main.cpp
时,
table.h
将包括'reader.h',其中将无限期地包括
table.h

解决这个问题至少有两种方法

第一种方法(在大多数情况下可能更可取)是在不需要完整定义的情况下向前声明类。例如,
有一个指向
读取器
的指针,不需要完整的定义:

新表 明智地使用前向声明有助于加快编译速度,也许更重要的是,减少循环依赖性

第二种方法是使用包括防护装置:

新表
无论是否使用转发声明,在所有头文件中使用include-guard可能不是一个坏主意,但我建议尽可能使用转发声明。

请提供一些代码。双重包含可以通过使用include-guards来解决:您可以在.h文件(如
extern
)中声明变量,但它应该在.cpp文件中定义。听起来您必须使用前向声明…并包含一个#pragma once或#ifndef..而没有难以诊断的代码,但我怀疑@PaulR有正确的修复方法。标题保护不是这里的问题您可以使用foward declare删除标题依赖项..总是更好..@Dory Zidon:是的,我同意,只是为了关联的目的。为什么这些答案被否决了?不幸的是,我的类的用户不应该知道关于表的任何信息您需要包括保护,这个答案与海报所抱怨的问题相同。您将多次定义表。在每个读卡器和扫描器中一次,然后再在主屏幕中一次。与海报抱怨的问题相同。为什么要投反对票?有人能解释一下吗?就我个人而言,我不会投反对票,但我也不会投反对票。在.h文件中缺少include-guard。但我猜可能有人不喜欢/不理解转发声明。我正在编辑我的答案,我在后面看到了你的评论,转发声明在减少标题依赖性方面非常有用,我花了数小时在有人创建的复杂标题依赖性的项目上。。
//Scanner.h
#pragma once //<---------- must use it so you do not have double include..
class Table; //forward decalre reduced dependendcy and no need to include h.
class Scanner {
    int ReadIntoTable(Table* pInTable);
}
//Scanner.cpp
// has method bodies that uses Table like   
#include "Table.h"
int Scanner::ReadIntoTable(Table* pInTable)
{
   pInTable->putData(123);
   return void.
}
//Table.h
#pragma once //<-------- use so you do not have double include.
class Table {
   getData();
   putData(int Data);
}
//Table.cpp 
// impelenation for table
#include "reader.h"

class Table
{
  Reader* mReader;
};
#include "table.h"
class Reader
{
};
#include "table.h"
#include "reader.h"

int main()
{
  Table table;
}
class Reader;
class Table
{
  Reader* mReader;
};
#ifndef TABLE_H
#define TABLE_H

#include "reader.h"

class Table
{
  Reader* mReader;
};