1

我正在尝试打印出统计对象的链接列表。我有一个统计类,其构造函数包含名称、级别和 exp。但我无法打印出来。这就是我尝试这样做的方式:

void Print(DoublyLinkedList<Datatype> p_list)
    {
        int index = -1;
        //Set up a new Iterator.
        //DoublyLinkedListIterator<Datatype> itr = getIterator();
        for(itr.Start(); itr.Valid(); itr.Forth())
        {
                index++;
                cout <<"Index: "<< index << "\tElement: " << itr.Item() << "\n";
        }
        cout <<"Number of Elements in the List: " << m_count << endl;
    }

这会导致 itr.item() 的 cout 出错。错误是:

Error 1 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Stats' (or there is no acceptable conversion)

这是来自 doublyLinkedlist 类,我在 main() 中设置了一个linkedList,然后我尝试从 main() 执行 list.print(list)。

在 Stats.cpp 中编辑

#include "Stats.h"
#include <string>
#include <iostream>

Validators validators2;

Stats::Stats()
{
    firstName = "";
    secondName = "";
    level = 0;
    experience = 0;
}
Stats::Stats(string firstName,string secondName, int level, int experience)
{
    firstName = firstName;
    secondName = secondName;
    level = level;
    experience = experience;

}
    string Stats :: getFirstName()
    {
        return firstName;
    }
    string Stats :: getSecondName()
    {
        return secondName;
    }
    int Stats :: getLevel()
    {
        return level;
    }
    int Stats :: getExperience()
    {
        return experience;
    }
    Stats Stats :: input()
    {
        firstName = "Please enter the First Name: ";
        string inputfirstName = validators2.getString(firstName);
        secondName = "Please enter the Second Name: ";
        string inputSecondName = validators2.getString(secondName);
        cout<< "Please enter the level: ";
        int inputLevel = validators2.getNum();
        cout<< "Please enter the experience: ";
        int inputExperience = validators2.getNum();

        Stats s1(inputfirstName,inputSecondName,inputLevel,inputExperience);
        return s1;

    }

在此先感谢...贝卡。

4

4 回答 4

1

该错误准确地说明了问题所在 - 运算符<<不知道如何处理您尝试打印的类型的对象。如果你想使用这样的代码,你必须为 Stats 类重载操作符。

于 2013-04-16T20:58:49.120 回答
1

正如它所说:你没有为你的班级统计定义 operator<<。你必须定义这个:

 std::ostream& operator<<(std::ostream& os, const Stats& s){
    //define what it means to cout<<Stats, for example:
    //print some attributes
    os<<"\nfirstName: "<<s.getFirstName();
    os<<"\nsecondName: "<<s.getSecondName();
    os<<"\nlevel: "<<s.getLevel();
    //and so on

    return os; // so chunk is possible os<<a<<b<<c
  }
于 2013-04-16T21:01:49.347 回答
0

根据您收到的消息,您只需为 Stats 类型声明 operator <<。

于 2013-04-16T21:02:01.863 回答
0

您需要提供

std::ostream & operator<<(std::ostream &os, const Stats& s)

它应该是免费的 funton,而不是 Stats 的成员

于 2013-04-16T21:02:05.683 回答