【发布时间】:2012-01-01 15:29:26
【问题描述】:
请原谅,但我不知道简短地给标题命名。
为什么我需要在头文件中声明一个重载的操作符才能使它在这个例子中工作:
头.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”内的命名空间中定义和声明的,那么为什么我需要在标题中再声明一次呢? 谢谢。
【问题讨论】:
-
为什么不在你的类中声明操作符??
-
@Alex :在课堂之外定义非赋值运算符通常被认为是一种好习惯。但是,运算符可以在标题内定义
inline... -
@Alex 我在这个例子的类 cos 之外定义了它,我目前正在努力解决这个问题,它可能是任何其他函数的同一个问题。谢谢。
-
刚刚在这里找到了一个很好的答案:stackoverflow.com/questions/4652932/… :)
标签: c++ namespaces operator-keyword