And*_*dry 2 c++ namespaces operator-overloading linker-errors
考虑使用以下头文件(c ++): myclass.hpp
#ifndef MYCLASSHPP_
#define MYCLASSHPP_
namespace A {
namespace B {
namespace C {
class myclass { /* Something */ };
myclass& operator+(const myclass& mc, int i);
}}}
#endif
Run Code Online (Sandbox Code Playgroud)
考虑实现文件: myclass.cpp
#include "myclass.hpp"
using namespace A::B::C;
myclass& operator+(const myclass& mc, int i) {
/* Doing something */
}
Run Code Online (Sandbox Code Playgroud)
考虑主文件: main.cpp
#include "myclass.hpp"
int main() {
A::B::C::myclass el = A::B::C::myclass();
el + 1;
}
Run Code Online (Sandbox Code Playgroud)
好吧,链接器告诉我有一个未定义的引用 A::B::C::operator+(A::B::C::myclass const&, int)
这有什么问题?
仅仅因为你using namespace A::B::C在实现文件中并不意味着在那里声明的所有东西都自动地存在于A::B::C命名空间中(否则,如果你是using多个命名空间,所有定义都会变得模棱两可).
myclass.cpp应该类似于:
namespace A {
namespace B {
namespace C {
myclass operator+(const myclass& mc, int i) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
或者(我觉得这个更干净):
using namespace A::B::C;
myclass A::B::C::operator+(const myclass& mc, int i) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
目前,编译器认为您已operator+在A::B::C命名空间中声明了一个函数,并且定义了一个根本不在命名空间中的不同函数,从而导致链接错误.