头文件中命名空间内的操作符声明
operator declaration within namespace in a header?
不好意思,我不知道怎么给标题起个简短的名字
为什么我需要在头文件中声明一个重载操作符来使它在这个例子中工作呢?
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;
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 将代码声明放入字中(引用操作符和解引用操作符混淆)
- 使用具体输出操作符的声明(带有具体签名)
- 用花括号代替赋值操作符声明和实例化作用域变量
- 头文件中命名空间内的操作符声明
- 在h和CPP文件中声明的操作符*操作符不匹配
- 如何在模板类中声明好友用户定义的文字操作符
- 如何声明操作符/重载函数来操作const变量和非const变量
- 如何声明比较操作符(小于)重载的模板特化
- 将比较操作符的重载定义/声明为库中的非成员函数
- 声明对对象的引用和赋值操作符
- 可以通过在基类中声明复制构造函数/操作符private来使派生类不可复制吗?
- 将内联非成员操作符的声明和定义分开的正确方法(链接器问题)
- 应该操作符声明为非成员非模板友元