STL列出程序员定义的类的容器类
我在访问存储在 STL list
中的类的成员函数时遇到问题。我的代码如下:
typedef Shape* shapePtr;
list <shapePtr> shapeList;
//skip alot...
case x:
{
cout << "Enter the height \n";
cin >> height;
cout << "Enter the base \n";
cin >> base;
//computation.
shapeList.push_back(new Triangle);
shapeList->setHeight(height);
shapeList->setBase(base);
break;
}
这导致 g++ 出现以下错误:
“->”的操作数具有非指针类型
错误:“*shapeList”中的“operator*”不匹配
case x:
{
cout << "Enter the height \n";
cin >> height;
cout << "Enter the base \n";
cin >> base;
//computation.
shapeList.push_back(new Triangle);
(*shapeList).setHeight(height);
(*shapeList).setBase(base);
break;
}
导致以下错误:
错误:“*shapeList”中的“operator*”不匹配
I'm having trouble accessing member functions of classes stored in an STL list
. My code is below:
typedef Shape* shapePtr;
list <shapePtr> shapeList;
//skip alot...
case x:
{
cout << "Enter the height \n";
cin >> height;
cout << "Enter the base \n";
cin >> base;
//computation.
shapeList.push_back(new Triangle);
shapeList->setHeight(height);
shapeList->setBase(base);
break;
}
This resulted in the following error with g++:
operand of ‘->’ has non-pointer type
error: no match for ‘operator*’ in ‘*shapeList’
case x:
{
cout << "Enter the height \n";
cin >> height;
cout << "Enter the base \n";
cin >> base;
//computation.
shapeList.push_back(new Triangle);
(*shapeList).setHeight(height);
(*shapeList).setBase(base);
break;
}
Resulted in the following error:
error: no match for ‘operator*’ in ‘*shapeList’
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
shapeList
指的是整个列表。如果您想要列表的最后一个元素,请使用shapeList.back()
,它返回对最后一个元素的引用(在本例中为shapePtr&
)。但是,由于您似乎正在调用特定于
Triangle
实例的方法(我假设它是Shape
的子类),因此您无法直接与shapeList.back()
因为Shape
没有这些方法。您需要做的是将Triangle
实例的分配与将其添加到shapeList
分开。分配Triangle
并将其存储在局部变量中。然后,您可以将其添加到该列表中,并通过该局部变量对其调用setHeight
和setBase
。shapeList
refers to the list as a whole. If you want the last element of the list, useshapeList.back()
, which returns a reference to the last element (ashapePtr&
in this case).However, since it looks like you're calling methods that are specific to
Triangle
instances (which I assume is a subclass ofShape
), so you can't interact directly withshapeList.back()
because aShape
doesn't have those methods. What you need to do is separate out the allocation of aTriangle
instance from adding it toshapeList
. Allocate theTriangle
and store it in a local variable. You can then add it to that list, and callsetHeight
andsetBase
on it via that local variable.