头文件中命名空间内的操作符声明



不好意思,我不知道怎么给标题起个简短的名字

为什么我需要在头文件中声明一个重载操作符来使它在这个例子中工作呢?

HEAD.H

#pragma once
namespace test {
    class A {
    public:
        A() : x(0) {}
        int x;
    };
    A& operator++(A& obj);  //this is my question
}

HEAD.CPP

#include "head.h"
namespace test {
    A& operator++(A& obj) {
        ++obj.x;
        return obj;
    }
}

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;
}

operator++是在"head.cpp"内部的命名空间中定义和声明的,所以为什么我需要在头文件中再声明一次呢?谢谢你。

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;
}

最新更新