在 class 方法中为与 class 在同一命名空间中定义的结构调用重载运算符

Call overloaded operator for struct defined in same namespace as class in class method

我在命名空间 saw 中定义了一个结构 coord。在同一个命名空间中,我还为 coord 重载了 operator<<。在 SAWBuilderbuildSAW() 方法中,我成功创建了一个 coord,但是当我尝试使用重载的 << 时,我在尝试编译时得到了 Undefined symbols for architecture x86_64:。但是,当我使用 std::out << coord.toString() << std::endl 时,该程序能够成功编译。如何在 SAWBuilder 的方法中成功访问 coord 的重载 operator<<?

// saw.hpp    
#ifndef __SAW_HPP__
#define __SAW_HPP__

#include <iostream>
#include <sstream>
#include <string>

using std::string;
using std::ostream;

namespace saw
{

    class SAWBuilder
    {
    public:
        SAWBuilder() {}

        int buildSAW() const;

        static const int SIZE_M = 100;

    };

    struct coord
    {
        int x;
        int y;
        int z;

        string toString();
    };

    ostream& operator<<(ostream& os, const coord& c);

}

#endif

实现文件:

// saw.cpp
#include "saw.hpp"

#include <iostream>
#include <sstream>
#include <string>

using std::string;
using std::ostringstream;

using std::endl;

namespace saw
{
    int SAWBuilder::buildSAW() const
    {
        int visited[SIZE_M][SIZE_M][SIZE_M] = {}; // initalize to zero

        coord starting_coord = coord{SIZE_M/2, SIZE_M/2, SIZE_M/2};

        std::cout << visited[0][0][0] << std::endl;

        std::cout << starting_coord << std::endl; // <- problem here!

        return 0;
    }

    string coord::toString()
    {
        ostringstream out;

        out << "[" << x << ", " << y << ", " << z << "]";

        return out.str();
    }

    ostream& operator<<(ostream& os, coord& c)
    {
        os << c.toString();
        return os;
    }

} 

主文件:

// main.cpp    
#include "saw.hpp"

using saw::SAWBuilder;

int main(int argc, char **argv)
{
    SAWBuilder saw;

    int a = saw.buildSAW();

    return a;
}

Makefile:

CXX = g++
CXXFLAGS = -Wall -pedantic -std=c++17 -g

Saw: main.o saw.o
    ${CXX} ${CXXFLAGS} -o $@ $^

main.o: saw.hpp
saw.o: saw.hpp
ostream& operator<<(ostream& os, const coord& c);

已声明,但

ostream& operator<<(ostream& os, coord& c)

被定义为不同的函数。注意缺少的 const。如果不是

,我会投票关闭作为错字
os << c.toString();

这要求 coord::toString 是一个 const 函数,并且可能是缺少 const 的原因:const-less 版本已编译,愚弄提问者认为它是正确的。

所以除了

ostream& operator<<(ostream& os, const coord& c) // added const
{
    os << c.toString();
    return os;
}

代码还需要

struct coord
{
    int x;
    int y;
    int z;

    string toString() const; // added const
};

及稍后实施

string coord::toString() const // added const
{
    ostringstream out;

    out << "[" << x << ", " << y << ", " << z << "]";

    return out.str();
}