我在命名空间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
答案 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
};