它有效,但它是对的

It works, but is it right?

本文关键字:有效      更新时间:2023-10-16

我是否借助对象动态数组中的方法填充对象字段。它有效,但它是对的吗?

EXAM* Array = new EXAM[n];
    for (int i=0;i<n;i++)
    {   
        cout<<endl;
        cout<<"Please type a name of the student: ";
        cin>>naMe;
        Array[i].setName(naMe);//Is it OK to access an object method this way in case of dynamic allocation?
        cout<<endl<<"Please type the date of exam: ";
        cin>>daTe;
        Array[i].setDate(daTe);
        cout<<"Please type mark: ";
        cin>>maRk;
        Array[i].setMark(maRk); 
    }
是的

,以下结构是等效的:

pointer[i].method();
(pointer + i)->method();
(*(pointer + i )).method();

类似这个:

object.method();
(&object)->method();
(*(&object)).method();

那只是用不同的语法来表达同样的事情。指针来自并不重要,即它是否指向动态分配的内存,本地或全局对象。使用指针和数组的语法保持不变。

是什么让你觉得不对?

如果标记和日期也是字符串(或在 setDate 和 setMark 函数中转换(,这看起来像是好的代码!