我无法访问存储在 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++ 的以下错误:
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;
}
导致以下错误:
error: no match for ‘operator*’ in ‘*shapeList’
最佳答案
shapeList
指的是整个列表。如果您想要列表的最后一个元素,请使用 shapeList.back()
,它返回对最后一个元素的引用(在本例中为 shapePtr&
)。
但是,由于看起来您正在调用特定于 Triangle
实例的方法(我假设它是 Shape
的子类),所以您不能直接与 shapeList.back()
交互,因为 Shape
没有这些方法。您需要做的是将 Triangle
实例的分配与将其添加到 shapeList
分开。分配 Triangle
并将其存储在局部变量中。然后您可以将它添加到该列表,并通过该局部变量对其调用 setHeight
和 setBase
。
关于c++ - 程序员定义类的 STL 列表容器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4289723/