如何在循环中从数组对象访问成员函数

How access member function from arrayobject in a loop

本文关键字:对象 访问 成员 函数 数组 循环      更新时间:2023-10-16

我正在尝试访问公共函数get_data(),以生成输出"这里",以查看是否从对象数组创建动态对象。那我该怎么做。

#include<iostream>
#include <conio.h>
using namespace std;
int counts = 0;
int no_of_array;
class Matrix
{
    int **dynamicArray;
public:
    Matrix()
    {
        counts++;
        dynamicArray = new int *[3];
        for (int i = 0; i < 3; i++)
        {
            dynamicArray[i] = new int[3];
        }
    }
    void get_data(){
        cout << "here n";
    }
};
int main()
{
    int newvalue = 1;
    int i;
    Matrix *array_object[100];
    int choice;
    while (newvalue == 1){
        cout << "Enter your choice n 1. for 2 matrix addition n 2. for 2 matrix multiplication n";
        cin >> choice;
        if (choice == 1)
        {
            cout << "how many array to add n";
            cin >> no_of_array;
            for (i = 0; i <= no_of_array; i++)
            {
                array_object[i] = new Matrix();
            }
            for (i = 0; i < no_of_array; i++)
            {
                array_object[i].get_data();
            }
        }
        else if (choice == 2)
        {
            Matrix mul;
            //  mul.multiplication();        
        }
        else
            cout << "Do enter correct choice n";
        cout << "press 1 to enter again and 0 to exit n";
        cin >> newvalue;
    }
    getch();
    return 0;
}

我正在尝试在这里检查,对于创建的所有对象,get_data函数将被调用或不被调用......但相反,我得到一个错误get_data尚未清除。

使用 array_object[i]->get_data(); 而不是 array_object[i].get_data();

对象尝试访问其类成员函数/变量时,将使用DOT(.)运算符Arrow(->)而如果对象是指针,则使用运算符。

现在,您宣布

Matrix *array_object[100]; 

这意味着array_object是一个Matrix指针数组。因此,您需要使用Arrow(->)而不是DOT(.)运算符。

Matrix *array_object[100];是指向矩阵类型的数组的指针。为了使用指针访问类成员,您应该使用->运算符。

for(i=0;i<no_of_array;i++)
{
       array_object[i]->get_data();
}