不能调用没有对象的成员函数 [英] cannot call member function without object

查看:167
本文介绍了不能调用没有对象的成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此程序具有用户输入 name / age 对,然后使用类输出。
这是代码。

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

#include "std_lib_facilities.h"

class Name_pairs
{
public:
       bool test();
       void read_names();
       void read_ages();
       void print();
private:
        vector<string>names;
        vector<double>ages;
        string name;
        double age;
};

void Name_pairs::read_names()
{
     cout << "Enter name: ";
     cin >> name;
     names.push_back(name);
     cout << endl;
}

void Name_pairs::read_ages()
{
     cout << "Enter corresponding age: ";
     cin >> age;
     ages.push_back(age);
     cout << endl;
}

void Name_pairs::print()
{
     for(int i = 0; i < names.size() && i < ages.size(); ++i)
             cout << names[i] << " , " << ages[i] << endl;
}

bool Name_pairs::test()
{
   int i = 0;
   if(ages[i] == 0 || names[i] == "0") return false;
   else{
        ++i;
        return true;}
}


int main()
{
    cout << "Enter names and ages. Use 0 to cancel.\n";
    while(Name_pairs::test())
    {
     Name_pairs::read_names();
     Name_pairs::read_ages();
     }
     Name_pairs::print();
     keep_window_open();
}

但是,在 int main()当我试图调用函数时,我得到不能调用任何名称的函数没有对象。我猜这是因为它的对于 variable.test variable.read_names 。我应该如何解决这个问题?

However, in int main() when I'm trying to call the functions I get "cannot call 'whatever name is' function without object." I'm guessing this is because it's looking for something like variable.test or variable.read_names. How should I go about fixing this?

推荐答案

您需要实例化一个对象才能调用其成员函数。成员函数需要一个对象进行操作;他们不能只是自己使用。 main()函数可以,例如,如下所示:

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();
}

这篇关于不能调用没有对象的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆