Skip to main content
GameDev.net gamedev.net
🔒 Locked

Cross reference in the same header

Started by Si_con Jul 31, 2011 at 1:02 PM 4 replies 1.7k views
Original Post
Si_con
Si_con
I have that:



#ifndef _FOO_H_
#define _FOO_H_

namespace NS {

class Foo;
float Func(const Foo& f1,const Foo& f2);

class Foo {
public:
float a,b;

Foo() {};
Foo(float n1,float n2):a(n1),b(n2) { };
Foo(const Foo& foo):a(foo.a),b(foo.b) { };
~Foo() {};

const Foo& operator = (const Foo& foo) {
a = foo.a;
b = foo.b;
return *this;
}

const Foo& operator * (const Foo& foo) {
a *= foo.a;
b *= foo.b;
return *this;
}

// Here float NS::Func(const NS::Foo&,const NS::Foo&) is known?
float Func(const Foo& foo) {
return NS::Func(*this,foo);
}
};

float Func(const Foo& f1,const Foo& f2) {
return f1.a*f2.a + f1.b*f2.b;
}

}; // namespace end

#endif






Im calling a function of the same namespace as the class, inside a member of the class, and that function take that class reference as arguments, im trying to make that work and put the declaration of class and external function on the top, so they are know in the rest of the file, but i still get errors, like this one:

multiple definition of `NS::Func(NS::Foo const&, NS::Foo const&)'|

How that can be done right ?




Si_con
Si_con
i think i realized that float Func(const Foo& f1,const Foo& f2) has to be in the cpp file, not in header as it was a templated function?
SiCrane
SiCrane
Either stick it in a source file or mark it inline.
Si_con
Si_con
if there are much declarations to put before the class, is a good practice to put all that declarations in a file and include it just before the main class declaration? something like that so it doesn't look so messy:



namespace NS {

#include "Foo_decl.h"

class Foo {

...

};



rip-off
rip-off
I would avoid doing that. Designing headers such that they cannot be included in isolation is brittle. Split the file into two headers if you wish, but ensure they work in isolation - e.g. they have the correct namespace declarations.
SiCrane
SiCrane
In general, creating a header designed to be included inside a namespace in another header is asking for trouble.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.