简体   繁体   English

有什么方法可以在参数化构造函数中输入 10 个学生的详细信息,并在 C++ 中使用带有对象数组的成员函数打印它

[英]Is there any way to enter 10 students detail in parameterized constructor and print it using member function with array of object in c++

I tried this code but when I am calling the member function inside the loop it is giving the garbage value of the details and when I am calling the member function outside the loop it is giving me error.我试过这段代码,但是当我在循环内调用成员函数时,它给出了细节的垃圾值,当我在循环外调用成员函数时,它给了我错误。

#include<iostream>
#include<string.h>

using namespace std;
class student
{   
  char name[10];
  int id,rollno;
  public:
  student(char name[10],int id,int rollno)
{
  strcpy(this->name,name);
  this->id=id;
  this->rollno=rollno;
    cout<<"the name of the student is:"<<name<<endl;
    cout<<"the id of the student is:"<<id<<endl;
    cout<<"the roll no of the student is:"<<rollno<<endl;
}

};

int main()
 {

 int id1,rollno1;
 char name1[10];
 for(int i=1;i<=2;i++)
{  
    cout<<"             enter the detail of the student "<<i<<"                       "<<endl;
    cout<<"enter the name of the student:";
    cin>>name1;
    cout<<"enter the id of the student:";
    cin>>id1;  
    cout<<"enter the roll no of the student:";
    cin>>rollno1;
    student d[]={student(name1,id1,rollno1)};
   d[i].print();
}

return 0;
}

You do not have a print member function.您没有print成员函数。 Your are initializing different arrays with one element inside the loop, if you want an array of 3 students, declare it outside the loop.您正在使用循环内的一个元素初始化不同的数组,如果您想要一个包含 3 个学生的数组,请在循环外声明它。 Something like this (note the comments):像这样(注意评论):

class student {
    std::string name;  // use string type
    int id, rollno;

   public:
    student(){}; // you need default contructor to declare the array

    student(std::string name, int id, int rollno)
        // propper way to initialize members
        : name(name), id(id), rollno(rollno) { }

    void print() { // create a print member
        std::cout << "Printing: " << name << " " << id << " " << rollno << "\n";
    }
};

int main() {

    student d[3]; // declare array (or 10, if you want 10 students)
                  // note that you can use std::array
                  // or std::vector for VLAs

    int id = 0;
    int rollno = 0;
    std::string name;

    for (auto& s : d) { // range based loop
        std::cin >> id >> name >> rollno; // not adding input validation, 
                                          // but you should do it
        s = {name, id, rollno};
        s.print();
    }
}

Live demo现场演示

I would also avoid using namespace std , it's pratical, I admit, but can cause all kinds of trouble, more info here .我也会避免using namespace std ,这很实用,我承认,但会导致各种麻烦,更多信息请点击此处

Here's your code review.这是您的代码审查。

#include <iostream> 
#include <string> // use string header instead of string.h

using namespace std; // it is strongly suggested that you don't use the whole header unless your intent is speeding up coding
class Student // capitalize classes
{
    char _name[10];// it is ok, however, if you use the <string> header, why would you go back to char type?
    int _id, _rollno;
public:
    Student(char name[10] /* this is just the array's first item passed! */, int id, int rollno)
    {
        // Don't use this->, use an underscore for one of the names. 
        // I use underscores for the encapsulated data
        strncpy_s(_name, name, 9);// a safer version
        _id = id; 
        _rollno = rollno;
        cout << "\nCtor says: ";
        cout << "the name of the student is: " << _name << endl;
        cout << "the id of the student is: " << _id << endl;
        cout << "the roll no of the student is: " << _rollno << endl;
        cout << '\n';
    }
    const char* getName() { return _name; }
    const int getId() { return _id; }
    const int getRollNo() { return _rollno; }
    // unless you overload operator<< , you have to make getters for your info, or make it public
};

int main()
{
    int id, rollno;// why 1? they won't intersect with the function
    char name[10];
    Student *s[2];//you must make that on the heap; otherwise you need a default constructor

    for (int i{ 0 }; i < 2; i++)// start with 0 and make it just <
    {
        cout << "enter the details of the student " << i << endl;// Why so many spaces?
        cout << "enter the name of the student: "; // add space after the colon
        cin >> name;// remember, you're limited to 9 chars + \n !!!
        cout << "enter the id of the student: ";
        cin >> id;
        cout << "enter the roll no of the student: ";
        cin >> rollno;
        //student d[] = { student(name,id,rollno) }; // you can't do this. It's not flexible.
        // You either assign enough space for the intended number of students in the stack, statically, or 
        // you lett it find more space in the heap = dynamically

        //this goes to the heap
        s[i]= new Student( name,id,rollno );// parentheses are well
        //s[i] = new Student{ name,id,rollno };// initializer list may also do

        //d[i].print();// what's to print here? It's not POD, cout needs instructions
        cout << "Stored data -> Id: " << 
            s[i]->getId() << ", Name: "  // -> dereferences the pointer, and s is a pointer now
            << s[i]->getName() << ", Roll no: " 
            // or you can dereference it
            << (*s[i]).getRollNo() 
            << endl << endl; // make some extra space here
        
    }

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 C++ 的类的默认构造函数中调用成员 object 变量的参数化构造函数? - How to call parameterized constructor of member object variable in a class' default constructor in C++? 使用参数化构造函数C ++动态分配对象数组 - Dynamical allocation of array of objects using parameterized constructor C++ 使用构造函数作为成员函数的C ++(用于序列化) - c++ using constructor as member function (for serialization) C ++错误:无法将“学生”转换为“学生*”…-函数中的结构数组 - C++ error: cannot convert 'students' to 'students*'… - struct array in function C ++多态:有没有办法找到对象成员函数的地址? - C++ polymorphism: Is there any way to find the address of an object's member function? C ++在对象构造函数和成员函数中使用const - C++ using const in object constructor and member functions 如何在 class 成员 function c++ 中打印 object 名称? - How to print object name in class member function c++? 使用模板时的 C++ 构造函数或递归成员函数 - C++ constructor or recursive member function when using templates C++ 通过指针 object 将 arguments 传递给参数化构造函数时出现程序错误? - C++ program error on passing arguments to the parameterized constructor by pointer object? C ++使用构造函数参数初始化成员数组 - C++ Initialize Member Array with Constructor Argument
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM