使用for_each从对象列表中调用打印函数

时间:2017-04-29 21:56:53

标签: c++ list

我需要使用for_each函数来调用对象列表shapeList中每个对象的print函数。当我将函数output作为for_each的最终参数时,我得到一个"无法确定哪个重载函数实例"输出"旨在。

void output(Point* point)
{
    point->print();
}

这是for_each

的输出函数
for_each(shapeList.begin(), shapeList.end(), output);

for_each语句

我已经看过其他涉及使用绑定和lambdas的解决方案,但这是一个类赋值,我不能使用这些方法。

非常感谢任何帮助。

#include <iostream>
#include <string>
#include <fstream>
#include <list>
#include <algorithm>

#define sz 12

using namespace std;

class Point
{
private:
    int x, y;
public:
    Point() { }
    Point(int a, int b)
        :x(a), y(b) { }
    // print function is pure virtual and that makes class Point an abstract class
    // a pure virtual function can have prototype only without definition
    // an abstract class can't be instantiated
    // its derived class must override this function in order to be a real class
    virtual void print() const = 0;
};

void Point::print() const
{
    cout << "\nPoint: ( "
         << x
         << " , "
         << y
         << " )";
}

///////////////////////////////////////////////////////////////////

class Circle : public Point
{
private:
    int radius;
public:
    Circle() : Point() { }
    Circle(int a, int b, int c)
        :Point(a, b), radius(c) { }

    virtual void print() const;
};

void Circle::print() const
{
    cout << "\nCenter of the Circle is at:  ";
    Point::print();
    cout << "\nRadius of the Circle is: "
         << radius;
}

/////////////////////////////////////////////////////////////////////

class Cylinder : public Circle
{
private:
    int height;
    char color[sz];
public:
    Cylinder() { }
    Cylinder(int a, int b, int r, int h, char clr[])
    :   Circle(a, b, r), height(h)
    { strcpy(color, clr); }

    virtual void print() const;
};

void Cylinder::print() const
{
    Circle::print();

    cout << "\nHeight of Cylinder is: "
         << height
         << "\nColor of Cylinder is: "
         << color
         << endl;
}

void load_list(list<Point*>&, char*); // 
void output(Point*&);

///////////////////////////////////////////////////////////////
int main()
{
    char clr[10];

    list<Point*> shapeList;////

    load_list(shapeList, clr);

    for_each(shapeList.begin(), shapeList.end(), output);

    return 0;
}

void load_list(list<Point*>& ptList, char *ch)
{
    char type;
    int x, y, r, h;

    ifstream infile("shapes.txt");
    if (!infile)
    {
        cout << "\nCan not open input file.";
        exit(1);
    }

    infile >> type;

    while (infile)
    {
        if (type == 'c')
        {
            infile >> x >> y >> r;
            ptList.push_back(new Circle(x,y,r));
        }
        else if (type = 'l')
        {
            infile >> x >> y >> r >> h >> ch;
            ptList.push_back(new Cylinder(x, y, r, h, ch));
        }
        infile >> type;
    }
}

void output(Point* point)
{
    point->print();
}

1 个答案:

答案 0 :(得分:0)

您声明函数通过引用获取指针(?)并且实现采用指针。