免责声明:我不熟悉使用c ++进行编程,我已阅读过几十个论坛,但无法找到我特定问题的答案。
我已经在下面包含了Point类的头文件和定义文件,以及一个调用重载ostream来打印Point的main函数。我找不到非成员重载运算符<<的定义的正确语法。如果我按照发布的方式使用它,我会收到错误消息:
未定义引用`Clustering :: operator<<(std :: ostream&,Clustering :: Point const&)
如果我在运算符<<之前添加Clustering ::我收到错误消息:
的std :: ostream的&安培; Clustering :: operator<<(std :: ostream&,const Clustering :: Point&)'应该在'Clustering'中声明 std :: ostream& Clustering :: operator<<(std :: ostream& os,const :: Clustering :: Point& point)
这段代码应该怎么写?
Point.h文件:
#ifndef CLUSTERING_POINT_H
#define CLUSTERING_POINT_H
#include <iostream>
namespace Clustering {
class Point {
int m_dim; // number of dimensions of the point
double *m_values; // values of the point's dimensions
public:
Point(int);
friend std::ostream &operator<<(std::ostream &, const Point &);
};
}
#endif //CLUSTERING_POINT_H
Point.cpp文件:
#include "Point.h"
//Constructor
Clustering::Point::Point(int i)
{
m_dim = i;
m_values[i] = {0};
}
std::ostream &operator<<(std::ostream &os, const Clustering::Point &point) {
os << "Test print";
return os;
}
Main.cpp的:
#include <iostream>
#include "Point.h"
using namespace std;
using namespace Clustering;`
int main() {
Point p1(5);
cout << p1;
return 0;
}
答案 0 :(得分:2)
您需要将std::ostream &operator<<
放入Point.cpp中的Clustering
命名空间
namespace Clustering {
std::ostream &operator<<(std::ostream &os, const Clustering::Point &point)
{
// ...
}
}