gpt4 book ai didi

c++ - 如何在循环中从 arrayobject 访问成员函数

转载 作者:搜寻专家 更新时间:2023-10-31 02:21:52 24 4
gpt4 key购买 nike

我正在尝试访问公共(public)函数 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 has not been decleared。

最佳答案

使用 array_object[i]->get_data(); 代替 array_object[i].get_data();

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

现在,你宣布

Matrix *array_object[100]; 

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

关于c++ - 如何在循环中从 arrayobject 访问成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30930177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com