如何在类名中创建一个带有变量名的类?

时间:2015-03-05 19:25:12

标签: c++ class variables int

所以,这是我的代码:

#include <iostream>
#include <conio.h>

using namespace std;

class rectangle {
public:
    double width;
    double height;
    rectangle(double, double);
    double area() { return (width*height);}
};

rectangle::rectangle(double a, double b) {
    width = a;
    height = b;
}

int main() {
    cout << "How many rectangles would you like to create? ";
    int rectNum;
    cin >> rectNum;

    for (int counter = 0; counter < rectNum; counter++) {
        int rectCount = 1;
        rectCount = counter + 1;
        double rectWidth, rectHeight;
        cout << "\nEnter width of rectangle " << rectCount << ": ";
        cin >> rectWidth;
        cout << "\nEnter height of rectangle " << rectCount << ": ";
        cin >> rectHeight;
        rectangle rect/*integer value of rectCount at current time*/(rectWidth, rectHeight);
    }

    return 0;
}

正如评论部分所说,我想创建一个名为rect的矩形,其后缀是整数rectCount的当前值。我该怎么做?提前谢谢!

3 个答案:

答案 0 :(得分:3)

这个习惯用法在C ++中永远不会有用。正确的方法是将矩形存储在std::vector之类的容器中,该容器会自动增长和缩小以满足您的需求。然后,您可以遍历向量,而不用担心实际上有多少元素。

std::vector<rectangle> rects(rectNum);

for (int counter = 0; counter < rectNum; counter++) {
    /* .. */
    rects.emplace_back(rectWidth, rectHeight);
}

实际上不需要循环。 std::vector的构造函数会为你处理它。

std::vector<rectangle> rects(rectNum, {rectWidth, rectHeight});

您需要添加<vector>才能使用std::vector

答案 1 :(得分:1)

必须在编译时定义变量名,因此您尝试执行的操作将无效。

答案 2 :(得分:0)

在C ++中无法动态设置类名。但是,静态变量可用于存储矩形的运行计数:

#include <iostream>
#include <conio.h>
using namespace std;

class rectangle 
{
    public:
        double width;
        double height;
        static int rectCount; //declare static variable
        rectangle(double, double);
        double area() { return (width*height);}
};

int rectangle::rectCount=0; //initialize static variable

rectangle::rectangle(double a, double b) 
{
    width = a;
    height = b;
    rectCount++;
}

int main() 
{
    cout << "How many rectangles would you like to create? ";
    int rectNum;
    cin >> rectNum;

    for (int counter = 0; counter < rectNum; counter++) 
    {
        int rectCount = 1;
        rectCount = counter + 1;
        double rectWidth, rectHeight;
        cout << "\nEnter width of rectangle " << rectCount << ": ";
        cin >> rectWidth;
        cout << "\nEnter height of rectangle " << rectCount << ": ";
        cin >> rectHeight;
        rectangle rect=rectangle(rectWidth, rectHeight);
        cout<<"rectCount value: "<<rectCount;
      }

return 0;
}