开发者

functions used in multiple classes

i sort of asked this before, bu开发者_如何学编程t i used what i was told to try to get my program to work:

Its probably because I am noob at C++, but I am having trouble using #ifndef due to the problem that my classes contain the same .h files. both s.h and t.h and main.cpp need the struct defined in r.h

i have

#include "s.h"
#include "t.h"

#ifndef r
#include "r.h"
#endlif

in my main cpp file

and in each of my s.h and t.h files, there is a

#ifndef r
#include "r.h"
#endlif
// and then its class

as well, but the compiler is giving me errors about expected nested-name-specifier before "namespace", unqualified id before using namespace std;, expected ';' before "namespace" in the r.h file even though all i have in the r.h file is:

#include <iostream>

using namespace std;
struct r{
// code
};

are the problems caused by the main cpp not importing certain libraries or something else? how do i fix it?


The #ifndef needs to go into the header files to prevent including it multiple times. So, your s.h would look something like this:

#ifndef S_H
#define S_H

// All of your s.h declarations go here

#endif

r.h would look something like this:

#ifndef R_H
#define R_H

// All of your r.h declarations go here

#endif

and so on.

This prevents header files from being included more than once. If you include the same header file multiple times in a single compilation unit the compiler will likely complain that the same symbol is being declared multiple times. It could also potentially induce an infinite loop during compilation if the same collection of headers are recursively included.


I'm hoping you are using r, s, and t to simplify your question.

Is it possible you are thinking that the statement with "struct r" DEFINES r for your program?

Those are two different kinds of definitions. One is a struct definition but you want to use a define:

#ifndef R_H
#define R_H
#include <iostream>

using namespace std;

struct r{
//code
};

#endif

(as andand already pointed out)

NOTE: I'm using the define R_H instead of r to avoid confusion. You want to use r for your struct and R_H for your the define in your header (well, actually the name of the module + "_H").


Compiler directives like #include and #ifdef are part of the "C preprocessor", which is actually a different programming language from C. So the preprocessor doesn't see your struct r. You'd need something like this in your r.h:

#include <iostream>
#define r
using namespace std;
struct something_that_isnt_called_just_r{
// code
};

That's why you're better off using the traditional include guards that @andand describes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜