Run time resolution c++ Namespace conflicts
File1.h
// Declaration
Class A
{
void Func();
}
//Along with some other stuff
File1.cpp
//Definition
A::Func()
{
}
// Along with some o开发者_StackOverflow中文版ther stuff
File2.h
class A
{
void Func();
}
File2.cpp
// Definition
File2::A::Func()
{
}
File3.cpp
#include "File1.h"
#include "File2.h"
//
Invokes Func()
Main1.cpp Main2.cpp
Main1.cpp File3.cpp and File2.cpp are build together
Main1.cpp File3.cpp and File1.cpp are build together I want to invokeFunc()
depending different linkage
But, it gives me compile time error.
How should I get around compile time error?
Is there standard way to get around above problem?
If I use namespace for File1 and File2 then I will not be able to invoke dynamically. Note: I can not change File1.h
Unlike Java (for one example), which enforces a 1:1 correspondence between classes and file names, C++ basically ignores file names completely. As such, to resolve the conflict between your two classes (both named A
), you can use namespaces:
//file1.h:
class A
void Func();
};
//file1.cpp:
A::Func() {}
//file2.h:
namespace f2 {
class A {
void Func();
};
}
// file2.cpp:
namespace f2 {
A::Func() {}
}
// main.cpp
#include "file1.h"
#include "file2.h"
int main() {
A f1a;
f2::A f2a;
f1a.Func(); // invokes Func declared in file1.h, which is in global namespace
f2a.Func(); // invokes Func declared in file2.h, which is in namespace f2
return 0;
}
It's not clear what you mean by invoking dynamically. Dynamic invocation sounds a lot like using a polymorphic function, which would require a common base class:
struct base {
virtual void Func() = 0;
};
struct A1 : public base {
virtual void Func() {}
};
struct A2 : public base {
virtual void Func() {}
};
int main() {
A1 a1;
A2 a2;
base *b[2] = { &a1, &a2 };
b[0]->Func(); // invokes A1::Func()
b[1]->Func(); // invokes A2::Func()
return 0;
}
精彩评论