【问题标题】:Passing Array of objects to same class C++将对象数组传递给同一类 C++
【发布时间】:2018-04-06 07:05:09
【问题描述】:

问题:声明一个名为“StudentRec”的类,它具有三个私有成员:int 类型的“enrolNo”、float 类型的“CGPA”和字符串类型的“branch”。声明一个名为“Student”的对象数组,其大小为 5,属于“StudentRec”类。编写公共成员函数:(i) void sort (StudentRec Student[], int N) 以相对于 'CGPA' 升序对数据进行排序; (ii) void print (StudentRec Student[], int N) 以显示已排序和未排序的学生记录。编写 main 来测试这些成员函数。

疑问 :我稍后会做的排序部分。我的疑问是,在下面的代码(倒数第二行)Student[5].print(Student, N ); 中是否是调用函数打印的正确方法?否则如何通过对象数组调用此函数Student[0].print(Student, N ) 也提供正确的输出。为什么 ?

#include<iostream>
#include<cstring>
using namespace std;

class StudentRec
{
    private:
        int enrolNo;
        float CGPA;
        string branch;
    public:
        void assign()
        {
            cin>>enrolNo>>CGPA>>branch;

        }
        void sort (StudentRec Student[], int N );
        void print(StudentRec Student[], int N )
        {
            int i;
            for(i=0; i<5; i++)
            {
                cout<<"Student"<<" "<<i<<"   "  ;
                cout<<Student[i].enrolNo<<" "<<Student[i].CGPA<<" "<<Student[i].branch<<endl;
            }
        }
};

int main()
{
    StudentRec Student[5];
    int i,N=5;
    for(i=0; i<5; i++)
        Student[i].assign();
    Student[5].print(Student,  N );
    return 0;
}

【问题讨论】:

  • Student[5].print(Student, N ); 调用 undefined behavior 因为您的数组只有 5 的大小(意味着最后一个有效索引是 4)
  • 那里没有Student[5]。您的课程是否解释了基本数组索引的工作原理?
  • 换个说法 - 为什么sortprint 不是static 成员函数?他们不依赖实例
  • Student[0].print ... 但是你的老师对编程和C++一无所知-
  • 是的。更好的选择是考虑您被告知的有关正确 C++ 实践的内容,以及如何更改设计以使用它们。但如果你这样做了,你将不得不希望你的老师不会因为没有遵循他们糟糕的设计而对你进行评分……这最终意味着你在编码方面比他们更好。

标签: c++ arrays


【解决方案1】:

正如已经指出的那样,Student[5].print(Student, N ); 调用未定义的行为,因为没有Student[5]。但是,您对 print 的实现实际上并没有使用调用它的对象,所以这可能就是它在实践中有效的原因。

为了给你的程序一个合理的设计,同时尽可能接近赋值,你可以声明函数static

static void print(StudentRec Student[], int N );

这意味着,虽然函数在类中声明并且可以访问类对象的私有成员,但它们不依赖于任何要调用的具体对象。然后你可以像这样使用它们:

StudentRec::print(Student, N);

附带说明,您的print 实现实际上并未使用参数N

【讨论】:

  • 是的,这应该保留在措辞中,因为静态成员函数仍然是成员函数。 (这是一个静态方法,而不是实例方法。)还要注意,您仍然可以在实例上调用静态方法,例如someStudentRec.print(whatever, n) 仍然可以工作,尽管它可能不是一个好的编写方式,因为它暗示一个实例方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 2016-09-20
  • 2015-02-01
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
相关资源
最近更新 更多