为与类方法中的类相同的名称空间中定义的结构调用重载运算符

时间:2019-04-06 18:01:19

标签: c++ operator-overloading linker-errors

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

SAWBuilder

实施文件:

// 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

1 个答案:

答案 0 :(得分:2)

PERFORM pg_sleep(time_frame);

已声明,但

ostream& operator<<(ostream& os, const coord& c);
而是定义了

,使其成为不同的功能。请注意缺少的ostream& operator<<(ostream& os, coord& c) 。如果不是

,我将投票关闭为错字
const

这需要os << c.toString(); 是const函数,并且可能是缺少的coord::toString丢失的原因:少了const的版本已被编译,使提问者认为它是正确的

除了

const

代码也需要

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