繁体   English   中英

使用正确的语法在名称空间中实现非成员的重载运算符

[英]Implement a non-member, overloaded operator, in a namespace, with correct syntax

免责声明:我是C ++编程的新手,我已经阅读了数十个论坛,并且找不到我特定问题的答案。

我在下面包括Point类的头文件和定义文件,以及一个主函数,该函数调用重载的ostream以打印Point。 我找不到非成员重载运算符<<的定义的正确语法。 如果按照发布方式进行操作,则会收到错误消息:

未定义对`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: :群集::点和点)

该代码应如何编写?

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

您需要将std::ostream &operator<<放在Point.cpp的Clustering名称空间中

namespace Clustering {

    std::ostream &operator<<(std::ostream &os, const Clustering::Point &point)
    { 
       // ... 
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM