Typedef数组指针参数的C ++ ostream重载

时间:2015-11-13 04:14:30

标签: c++ operator-overloading typedef function-parameter extraction-operator

如何避免创建" typedef Point * pPoint;"对于"<<" - 过载功能中的第二个参数?

这样做的正确方法是什么?我在哪里可以阅读更多相关信息?

#include <iostream>
using namespace std;

typedef float Point[3];
typedef Point* pPoint;


ostream & operator << (std::ostream &os, const pPoint & p )
    {
        int size = sizeof(p);
        for (int i=0; i<size; i++)
        {
            os << "[" << p[i][0] << "," << p[i][2] << "," << p[i][2] << "]" << endl;
        }

        return os;
    }

int main() {

    Point corners[8] = {
    { 1, -1, -5},
    { 1, -1, -3},
    { 1, 1, -5},
    { 1, 1, -3},
    {-1, -1, -5},
    {-1, -1, -3},
    {-1, 1, -5},
    {-1, 1, -3}
    };

    cout << "Point:" << corners<< endl;

    return 0;
}

3 个答案:

答案 0 :(得分:0)

如果您在64位系统中进行编译,您的代码可能会有效,但这只是巧合。 sizeof(p)是指针的大小,而不是它指向的数组。

您可能希望将Point数组替换为STL容器,或者使运算符按数组大小进行模板化并将引用传递给数组。

答案 1 :(得分:0)

您正在寻找:

template<size_t N>
ostream & operator<< (std::ostream &os, Point const (&p)[N])

使用N作为循环条件中的计数。

这会通过引用传递整个数组,因此可以在函数中使用N

您现有的代码会将指针传递给第一行,因此您无法检索大小8。而是使用垃圾值sizeof(p),这是存储指针所需的字节数,与数组维度无关。

答案 2 :(得分:0)

感谢您的解释。纠正上面的代码。

 #include <iostream>
 using namespace std;

 typedef float Point[3];

template<size_t N>
ostream & operator<< (std::ostream &os, Point const (&p)[N])
{
    int size = sizeof(p)/sizeof(*p);

    for (int i=0; i<size; i++)
    {
        os << "[" << p[i][0] << "," << p[i][2] << "," << p[i][2] << "]" << endl;
    }

    return os;
}

int main() {

Point corners[4] = {
            { 1, -1, -5},
            { 1, -1, -3},
            { 1, 1, -5},
            { 1, 1, -3},
            };

cout << "Point:" << corners<< endl;

return 0;
}