注册 登录
编程论坛 VC++/MFC

products[i,j]与products[i][j]是不是一个意思?为什么不能互换使用?

fgfdfg 发布于 2011-07-30 23:13, 382 次点击
Visual C++ 2010,C++/CLI平台

一、正确原程序如下:
#include "stdafx.h"
using namespace System;
int main(array<System::String ^> ^args)
{
    const int Size(12);
    array<int, 2>^ products(gcnew array<int, 2>(Size, Size));
    Console::WriteLine(L"Here is the {0} times table.", Size);

    for(int i = 0; i <= Size; i++)
        Console::Write(L"______");

    Console::WriteLine();

    Console::Write(L"     |");

    for(int i = 1; i <= Size; i++)
        Console::Write(L"{0,4} |", i);

    Console::WriteLine();

    for(int i = 0; i <= Size; i++)
        Console::Write(L"_____|");

    Console::WriteLine();

    for(int i = 0; i < Size; i++)
    {
        Console::Write(L"{0,4} |", i + 1);

        for(int j = 0; j < Size; j++)
        {
            products[i,j] = (i + 1) * (j + 1);
            Console::Write(L"{0,4} |", products[i,j]);

        }

        Console::WriteLine();
    }

    for(int i = 0; i <= Size; i++)
        Console::Write(L"______");

    Console::WriteLine();
    return 0;
}

但是我将
products[i,j] = (i + 1) * (j + 1);
Console::Write(L"{0,4} |", products[i,j]);
换成
products[i][j] = (i + 1) * (j + 1);
Console::Write(L"{0,4} |", products[i][j]);
就提示错误:
1>test.cpp(37): error C3262: 无效的数组索引: 1 维度为 2-维“cli::array<Type,dimension> ^”指定
1>          with
1>          [
1>              Type=int,
1>              dimension=2
1>          ]
1>test.cpp(37): error C2109: 下标要求数组或指针类型
1>test.cpp(38): error C3262: 无效的数组索引: 1 维度为 2-维“cli::array<Type,dimension> ^”指定
1>          with
1>          [
1>              Type=int,
1>              dimension=2
1>          ]
1>test.cpp(38): error C2109: 下标要求数组或指针类型

这是什么原因?为什么这里只能用products[i,j],而不能用products[i][j]

二、正确原程序如下:
#include "stdafx.h"
using namespace System;
int main(array<System::String ^> ^args)
{
    array<array<String^>^>^ grades = gcnew array<array<String^>^>
    {
        gcnew array<String^>{"Al", "Blue"},
        gcnew array<String^>{"Lily", "Lucy"},
        gcnew array<String^>{"Line", "Bile"},
        gcnew array<String^>{"King", "Jack"},
        gcnew array<String^>{"Bete", "Tome"},
    };

    wchar_t gradeLetter('A');
    for(int i = 0; i < grades -> Length; i++)
    {
        Console::WriteLine();
        Console::WriteLine(L"Students of the {0} grade:", gradeLetter++);
        for(int j = 0; j < grades[i] -> Length; j++)
            Console::Write(L"{0,12}", grades[i][j]);
    }
    Console::WriteLine();
    return 0;
}

但是我将
Console::Write(L"{0,12}", grades[i][j]);
换成
Console::Write(L"{0,12}", grades[i,j]);
就提示错误:
1>test.cpp(64): error C3262: 无效的数组索引: 2 维度为 1-维“cli::array<Type> ^”指定
1>          with
1>          [
1>              Type=cli::array<System::String ^> ^
1>          ]

这是什么原因?为什么这里只能用grades[i][j],而不能用grades[i,j]

谢谢。
0 回复
1