cannot call member function without object

后端 未结 4 1620
遥遥无期
遥遥无期 2020-11-27 19:09

This program has the user input name/age pairs and then outputs them, using a class. Here is the code.

#include \"std_lib_facilitie         


        
相关标签:
4条回答
  • 2020-11-27 19:21

    just add static keyword at the starting of the function return type.. and then you can access the member function of the class without object:) for ex:

    static void Name_pairs::read_names()
    {
       cout << "Enter name: ";
       cin >> name;
       names.push_back(name);
       cout << endl;
    }
    
    0 讨论(0)
  • 2020-11-27 19:27

    You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main() function could, for example, look like this:

    int main()
    {
       Name_pairs np;
       cout << "Enter names and ages. Use 0 to cancel.\n";
       while(np.test())
       {
          np.read_names();
          np.read_ages();
       }
       np.print();
       keep_window_open();
    }
    
    0 讨论(0)
  • 2020-11-27 19:31

    You are right - you declared a new use defined type (Name_pairs) and you need variable of that type to use it.

    The code should go like this:

    Name_pairs np;
    np.read_names()
    
    0 讨论(0)
  • 2020-11-27 19:33

    If you want to call them like that, you should declare them static.

    0 讨论(0)
提交回复
热议问题