使用此时写入内存冲突错误

时间:2018-05-31 09:21:31

标签: c++ this

void main()
{
    shape *a[200];
    int user_choice = 0, pilihan = 0, count = 0;
    while (user_choice != 3)
    {
        cout << "---===Menu===---" << endl;
        cout << "(1). Add Shape" << endl;
        cout << "(2). Show All" << endl;
        cout << "(3). Exit" << endl;
        cout << "Masukkan Pilihan Anda : ";
        cin >> user_choice;
        if (user_choice == 1)
        {
            cout << "---===Menu===---" << endl;
            cout << "(1). Lingkaran" << endl;
            cout << "(2). Segitiga" << endl;
            cout << "(3). Back" << endl;
            cout << "Masukkan Pilihan Anda : ";
            cin >> pilihan;
            if (pilihan == 1)
            {
                count++;
                int radius;
                cout << "Masukkan Radius : ";
                cin >> radius;
                a[count] = new lingkaran(radius);
            }
            else if (pilihan == 2)
            {
                count++;
                int alas, tinggi;
                cout << "Masukkan Alas : ";
                cin >> alas;
                cout << "Masukkan Tinggi : ";
                cin >> tinggi;
                a[count] = new segitiga(alas, tinggi);
                /*  for (int x = 0; x < count; x++)
                {
                    a[x]->set2(alas, tinggi);
                }
                count++;*/
            }
            else if (pilihan == 3)
            {
                break;
            }
        }
        else if (user_choice == 2)
        {
            for (int x = 0; x < count; x++)
            {
                cout << "test1" << endl;
                a[x]->show();
                cout << "test2" << endl;
                cout << endl;
            }
        }
    }
}

所以基本上,我认为我做得对,但我的虚空秀(),他们只是打开然后自己关闭..任何帮助建议?,* segitiga = triangle,* lingkaran = circle

for (int x = 0; x < count; x++)
{
    cout << "test1" << endl;
    a[x]->show();
    cout << "test2" << endl;
    cout << endl;
}

1 个答案:

答案 0 :(得分:0)

您在索引1处创建第一个对象,而不是0 因此,第一个数组元素具有不确定的值,只是你运气崩溃。

如果count是您的元素数量,那么您也想要创建下一个对象的索引。

在添加新元素后增加count

if (pilihan == 1)
{
    int radius;
    cout << "Masukkan Radius : ";
    cin >> radius;
    a[count] = new lingkaran(radius);
    count++;
}

或写入count-1:th元素:

if (pilihan == 1)
{
    count++;
    int radius;
    cout << "Masukkan Radius : ";
    cin >> radius;
    a[count-1] = new lingkaran(radius);
}

但在我看来,这种变体有点难以理解。