如何将成员函数引入范围

How to bring member function in scope?

本文关键字:范围 函数 成员      更新时间:2023-10-16

所以我调用了一个函数,该函数将输入作为极限i和对象数组h。

#include<iostream>
#include<vector>
using namespace std;
class hotel
{
private:
    string name,add;
    char grade;
    int charge,no;
public:
    void getdata();
    void putdata();
    void grade_print(int,hotel[]);
    void room_charge();
    void top2();
};
void hotel::getdata()
{
    cout<<"Add Name: ";
    getline(cin>>ws,name);
    cout<<"Add Addres: ";
    getline(cin>>ws,add);
    cout<<"Enter grade,room charge and no. of rooms: ";
    cin>>grade>>charge>>no;
}
void hotel::putdata()
{
    cout<<name<<endl<<add<<endl<<grade<<endl<<charge<<endl<<no;
}
void hotel::grade_print(int num,hotel h[])
{
    int i,j,k; char val;
    for(i=0;i<num;i++)
    {
        val=h[i].grade;
        for(j=0;j<num;j++)
        {
            if(h[j].grade==val)
            {
                cout<<h[j].grade<<endl;
                h[j].grade=' ';
            }
        }
    }
}
int main()
{
    std::vector <hotel> h(1);
    int i=0,j;
    cout<<"Want to add hotel? Press 1: ";
    cin>>j;
    while(j==1)
    {
        h[i].getdata();
        h.resize(2);
        i++;
        cout<<"Want to add more? Press 1 for yes, 0 for no: ";
        cin>>j;
    }
    grade_print(i,h);
}

此处的错误显示grade_print超出范围。此外,等级是私有成员,但由成员函数调用。那么为什么它表明等级不能被称为。请告诉我为什么会这样,我能做些什么来修复它?编辑1:将函数声明为静态无效无济于事,因为编译器显示函数不能声明为静态无效。

D:C++ Programstestfile.cpp|30|error: cannot declare member function 'static void hotel::grade_print(int, hotel*)' to have static linkage [-fpermissive]|

我所知,grade_print打印出有关一组作为参数传递的酒店的信息。如果有一个作用于某个类的组的函数,则该函数不应是该类的成员。相反,它应该只是一个与任何类无关的函数。这也修复了您的范围问题,因为它将具有全局范围。

如果我的论点看起来很奇怪,可以这样想。假设我有一个名为 number 的类,以及一个名为 print_nums 的函数,该函数打印传递给它的numbers数组。我会print_nums全局函数还是类number的成员?第一个,对吧?第二个,虽然会起作用,但实际上没有意义。

grade_print(i, h);

非静态成员函数应该在特定对象上调用,例如:

h[i].grade_print(i, h);

但是,在您的情况下grade_print必须是静态的,因此应该像这样声明:

static void grade_print(int,hotel []);

定义就像正常一样。另外,在grade_print静态之后,你必须像这样称呼它:

hotel::grade_print(i, h);
相关文章: