为在与类方法中的类相同的命名空间中定义的结构调用重载运算符
Call overloaded operator for struct defined in same namespace as class in class method
我在命名空间saw
中定义了一个结构coord
。在同一个命名空间中,我还重载了coord
的operator<<
。在buildSAW()
方法SAWBuilder
中,我成功地创建了一个coord
但是当我尝试使用重载<<
时,当我尝试编译时会Undefined symbols for architecture x86_64:
。该程序能够成功编译,但是当我使用std::out << coord.toString() << std::endl
时。如何在 for SAWBuilder
方法中成功访问重载的operator<<
coord
?
// 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
版本,欺骗提问者认为它是正确的。
所以除了
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();
}
相关文章:
- 在类构造函数中定义结构变量的参数
- C++ 通过函数传递自定义结构
- 在C++中循环访问自定义结构列表的小问题
- 如何在Qt中使用QDataStream将自定义结构保存/加载到二进制文件中?
- 如何在C++中的.h文件中的类中定义结构
- 如何定义C结构:C-linkage和udt
- 结构向量中自定义结构函数的内存使用
- 类型转换自定义结构
- 使用结构绑定更改自定义结构的值
- 信号槽自定义结构问题
- 如何将unordered_set与自定义结构一起使用?
- 定义结构中没有默认构造函数的类
- 为什么C++在自定义结构向量时会出现 ostream 重载问题?
- 通过自定义结构和链接列表类中的C 中的哈希表
- 从自定义结构数组中提取数据
- 无法使用自定义结构的属性
- 通过引用将自定义结构的向量传递给 boost::compute 闭包或函数
- 如何从输入中定义的"external" int 定义结构中的数组大小
- 定义结构数组
- 在Cython中定义C 结构返回类型