头中名称空间内的运算符声明?

cod*_*ddy 1 c++ namespaces operator-keyword

请原谅,但我不知道在短时间内给这个标题命名.

为什么我需要在标头中声明一个重载的运算符,以使其在此示例中起作用:

HEAD.H

#pragma once

namespace test {
    class A {
    public:
        A() : x(0) {}
        int x;
    };
    A& operator++(A& obj);  //this is my question
}
Run Code Online (Sandbox Code Playgroud)

HEAD.CPP

#include "head.h"

namespace test {
    A& operator++(A& obj) {
        ++obj.x;
        return obj;
    }
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#include <iostream>
#include "head.h"
using namespace std;
using namespace test;

int main() {
    A object;
    ++object;  //this won't work if we delete declaration in a header
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

operator ++是在"head.cpp"中的命名空间中定义和声明的,那么为什么我需要在头文件中再次声明它呢?谢谢.

Vla*_*lad 5

CPP文件彼此独立编译,它们只能看到它们包含的头文件(实际上它们在编译之前以文本方式添加到CPP的源代码中).因此,您将使用头文件通知编译器存在具有该签名的函数(无论是运算符重载).

然后,您的CPP文件的输出由链接器组合在一起,当您发现是否已经在头文件中声明了一个函数但从未麻烦地实现它时.

命名空间的简单示例:

#include <iostream>

namespace test{
    int f() { return 42; }
    int g() { return -1; }
}

namespace other{
    int f() { return 1024; }
}

using namespace other;

int main(){

    //error: 'g' was not declared in this scope
    //std::cout << g() << std::endl;

    std::cout << test::f() << std::endl; //42
    std::cout << f() << std::endl; //1024

    return 0;
}
Run Code Online (Sandbox Code Playgroud)