从同一类的另一个方法调用数组2D-C++

Call Array 2D From Another Method Same Class - C++

本文关键字:方法 另一个 调用 数组 2D-C++ 一类      更新时间:2023-10-16

我有代码:

    #include <iostream>
using namespace std;
class tokoKomputer
{
    public:
        void notebook();
        void printNotebook();
};
void tokoKomputer::notebook()
{
    string notebook[][8]=
    {
        {"MERK", "NO SERI", "HARGA", "STOK", "MEMORY", "HDD", "GPU", "DISPLAY"},
        {"Asus", "ASN0002", "2500000", "9", "1GB", "250GB", "128MB", "10"},
        {"Fujitsu", "FJN0001", "5500000", "12", "1GB", "320GB", "256MB", "14"},
        {"Fujitsu", "FJN0005", "6500000", "4", "4GB", "250GB", "1GB", "14"}
    };  
}
void tokoKomputer::printNotebook()
{
    cout<<notebook[1][3]<<endl;
    cout<<notebook[2][3]<<endl;
}
int main()
{
    tokoKomputer run;
    run.printNotebook;
}

但是,如果我编译代码ubuntu终端总是给我消息

coba.cpp:33:18: error: invalid types ‘<unresolved overloaded function type>[int]’ for array subscript
coba.cpp:34:18: error: invalid types ‘<unresolved overloaded function type>[int]’ for array subscript

有什么错误?请给我点击以解决代码

thx

string notebook[][8]是方法的本地变量,您需要传递一个引用,或者只为类提供一个私有的notebook[][]变量。

notebook[1][3]
notebook[2][3]

以上内容不在printNotebook的范围内定义为

string notebook[][8]

在notebook()方法结束后超出范围。

编辑:确保您重命名它,因为您不能拥有具有相同名称的方法和变量成员

再次编辑:这里有一些示例代码可以让您的示例站稳脚跟,这可能是NOT最简单或最好的方法,但确实编译并工作。

#include <iostream>
#include <string>
using namespace std;
class tokoKomputer
{
    public:
        void notebook();
        void printNotebook();
        string myNotebook[4][8];  
};
void tokoKomputer::notebook()
{
    string myTempNotebook[4][8] = {
        {"MERK", "NO SERI", "HARGA", "STOK", "MEMORY", "HDD", "GPU", "DISPLAY"},
        {"Asus", "ASN0002", "2500000", "9", "1GB", "250GB", "128MB", "10"},
        {"Fujitsu", "FJN0001", "5500000", "12", "1GB", "320GB", "256MB", "14"},
        {"Fujitsu", "FJN0005", "6500000", "4", "4GB", "250GB", "1GB", "14"}
    };  // This syntax will only work for initializing an array, not setting it later
    for (int i = 0; i <= 3; i++)
    {
        for (int j = 0; j <= 7; j++)
        {
            myNotebook[i][j] = myTempNotebook[i][j];
        }
    }
};
void tokoKomputer::printNotebook()
{
    cout << myNotebook[1][3] << endl;
    cout << myNotebook[2][3] << endl;
};
int main()
{
    tokoKomputer run;
    run.notebook();
    run.printNotebook();
    string hello;
    cin >> hello;  // this was just here to keep console open
};
相关文章: