gpt4 book ai didi

c++ - 如何打印对象的 LinkedList

转载 作者:行者123 更新时间:2023-11-30 04:19:07 25 4
gpt4 key购买 nike

我正在尝试打印出统计对象的链接列表。我有一个带有包含名称、级别和 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;

}

提前致谢...贝卡。

最佳答案

如其所说:您没有为类统计信息定义运算符<<。你必须这样定义:

 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
}

关于c++ - 如何打印对象的 LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16046884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com