所以我一直在建立一个我发现的类的小例子,以便更好地为将来的C ++编码分配做好准备。尝试编译此代码会给我一个错误:" classExample.cpp:12:2:错误:' list'没有命名类型"。
唯一的问题是,我绝对将它的类型指定为Rectangle *,如下面的代码所示。我做错了什么?
// classes example
#include <iostream>
#include <stdlib.h>
#include <string>
#include <sstream>
using namespace std;
class setOfRectangles {
list<Rectangle*> rectangles;
};
class Rectangle {
int width, height; //class variables
public: //method constructors
Rectangle(){width = 0; //constructor for rectangle
height = 0;}
Rectangle(int i, int j){width = i; height=j;}
void set_values (int,int);
string toString();
int area() {return width*height;}
int perimeter(){return (2*width)+(2*height);}
};
void Rectangle::set_values (int x, int y) { //fleshing out class method
width = x;
height = y;
}
string Rectangle::toString()
{
/*
Prints information of Rectangle
Demonstrates int to string conversion (it's a bitch)
*/
std::stringstream sstm; //declare a new string stream
sstm << "Width = ";
sstm << width;
sstm << "\n";
sstm << "Height = ";
sstm << height;
sstm << "\n";
sstm << "Perimeter = ";
sstm << perimeter();
sstm << "\n";
return sstm.str(); //return the stream's string instance
}
int main (int argc, char* argv[]) {
if(argc != 3)
{
cout << "Program usage: rectangle <width> <height> \n";
return 1;
}
else
{
Rectangle rect = Rectangle(2,3); //new instance, rectangle is 0x0
cout << "area: " << rect.area() << "\n";
cout << rect.toString() << endl;
//call this method
rect.set_values (atoi(argv[1]),atoi(argv[2]));
cout << "area: " << rect.area() << "\n";
cout << rect.toString() << endl;
return 0;
}
}
答案 0 :(得分:2)
您需要为list
添加正确的标头:#include <list>
另外,为什么要在C ++应用程序中包含C头<stdlib.h>
?是atoi
吗?如果是这样,你应该研究如何以正确的方式在C ++中进行强制转换。或者包括<cstdlib>
(这是相同标题的C ++版本)。
另外,你需要移动它:
class setOfRectangles {
list<Rectangle*> rectangles;
};
在声明class Rectangle
之后,或者编译器不知道Rectangle是什么。