我是C++的新手,我正在尝试执行以下操作:
1)我创建了一类名为Objects的对象,它包含对象的名称和一个用于标识它们的数字.
2)我创建了一个继承自list的类Group,如下所示:
#include "objects.h"
#include <list>
#include <iostream>
#include <string> using namespace std;
class Group : public std::list<Objects*> { private:
string groupname;
public:
Group(string groupname);
virtual ~Group() {} //destructor
virtual string getGroupName() const;
virtual void showlist(ostream & sl) const; };
Run Code Online (Sandbox Code Playgroud)
3)然后,我实现了方法showlist如下:
void Groupe::showlist(ostream & sl) const{
printf("I'm here 1\n");
for(auto it = this->begin(); it != this->end(); it++){
printf("I'm here 2\n");
sl << this->getGroupName() << "test" << "test\n" << endl;
std::cout << "I'm alive";
} }
Run Code Online (Sandbox Code Playgroud)
getGroupName方法如下:
string Group::getGroupName() const{
return groupname;
}
Run Code Online (Sandbox Code Playgroud)
4)在主程序中,我创建了一个指向Group类型变量的指针.代码编译没有任何错误,但是当我执行它时,我意识到程序进入方法showlist并在没有执行for循环的情况下退出.我通过使用printf放置消息来测试它.只是消息"前方法","我在这里1",以及"后方法"在终端显示.它没有显示"我在这里2".我从main打电话如下:
Group *lgroup = new Group[5] {Group("g1"), Group("g2"),Group("g3"),Group("g4"),Group("g5")};
printf("Before method\n");
lgroup->showlist(sl);
printf("After method\n");
cout << sl.str() << endl;
Run Code Online (Sandbox Code Playgroud)
你能帮我理解循环没有被执行的原因吗?
更新
该程序没有进入循环,因为列表是空的,如成员的答案中所述.
至于继承的这种情况List是一个约束,我已经填写了main函数中的列表,如下所示:
Groupe *lgroup1 = new Groupe("g1");
Object *objets[3];
objets[1] = new File("/home/Documents", "b2.jpg",0,0);
objets[2] = new File("/home/Documents", "b3.jpg",0,0);
objets[3] = new File("/home/Documents", "b4.jpg",0,0);
lgroup1->push_back(objets[1]);
lgroup1->push_back(objets[2]);
lgroup1->push_back(objets[3]);
Run Code Online (Sandbox Code Playgroud)
哪个File类继承自类Objects.这样程序就可以编译和执行.在命令行中,示出的类的属性Groupe,是g1.我想使用display已经在类中实现的方法,Objects但是当我尝试这样做时,编译器会显示以下错误:
error: 'const class Group' has no member named 'display'
sl << this->display(cout) << '\n' << endl;
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是如何让类Group继承这两个方法List(已经完成)和Objects?