c++ - 为 typedef 定义的对象添加 ofstream 方法

标签 c++ typedef

假设在我的 C++ 代码中定义一个自定义类型来处理 3d 中的 vector :

typedef tuple<double,double,double> vector3d;

是否可以向其中添加一个方法,以便我可以使用以下方法快速输出它们的坐标:

vector3d somevector(1,1,1);
cout << somevector << "\n";

我知道我可以将这些对象包装在 classstruct 中,但是否可以更直接地做到这一点?

最佳答案

过载 streaming operator对于 ostream

typedef tuple<double,double,double> vector3d;

ostream& operator<<(ostream& os, const vector3d& vec)
{
    os << '(' <<
          std::get<0>(vec) << ',' <<
          std::get<1>(vec) << ',' <<
          std::get<2>(vec) << ')';
    return os;
}

int main(int argc, char *argv[])
{
    cout << vector3d(1, 2, 3);
    return 0;
}

关于c++ - 为 typedef 定义的对象添加 ofstream 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34815144/

相关文章:

c++ - 如何/何时使用虚拟析构函数?

c++ - 具有可变参数的提取函数

header 或 .cpp 中类变量的 C++ 声明?

c++ - 我是否应该同步双端队列

c++ - Arduino 上的结构 : function() 'does not name a type'

.net - 为什么 .NET 中的泛型类型在 TypeDef 中有一个条目而在 TypeSpec 中有另一个开放类型条目?

c - 如何检查 typedef 结构的内部 typedef 结构是否为 NULL?

c++ - QPixmap 不显示我的图片

c++ - Typedef 和函数声明不能​​一起工作

c++ - 将 std::string 转换为 ci_string