【发布时间】:2016-02-23 15:17:50
【问题描述】:
我是 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; };
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";
} }
而getGroupName方法如下:
string Group::getGroupName() const{
return groupname;
}
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;
您能帮我理解为什么没有执行循环吗?
更新
程序没有进入循环,因为列表是空的,正如成员的回答中所解释的那样。
至于这个case继承自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]);
其中File 是一个继承自类Objects 的类。这样程序编译并执行。在命令行中显示了类Groupe 的属性,即g1。我想使用 display 类中已经实现的方法 Objects 但是当我尝试这样做时,编译器会显示此错误:
error: 'const class Group' has no member named 'display'
sl << this->display(cout) << '\n' << endl;
那么,我的问题是如何让Group 类继承List(已经完成)和Objects 的方法?
【问题讨论】:
-
在你的代码中设置一个断点并单步执行它,看看它是否真的在跳过循环或者可能发生什么。
-
您不想从标准容器继承。使用聚合而不是继承。
-
要在更新后回答您的问题,请查看multiple inheritance