如何将成员函数引入范围
How to bring member function in scope?
所以我调用了一个函数,该函数将输入作为极限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);
相关文章:
- 通过函数指针定义类范围之外的方法
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 有没有办法在另一个函数中加入线程?(即超出其自身范围)
- 从函数返回范围视图时,带有std::span:中间对象所有权的C++Ranges-v3
- 在可变参数函数中转发特定范围的参数
- std::线程不是全局变量,但在到达创建它的函数的末尾时不会超出范围?
- 使函数参数默认为周围范围
- 在 gcc/clang (C++) 中获取函数范围之外的标签地址
- C++ 在编译过程中 strtok 函数 Eclipse 说没有在范围内声明?
- 包含来自另一个文件的函数会导致范围错误(openFoam)
- 定义一个 void f(void) 函数,但使用来自同一范围的变量?
- 私有在函数定义/实现的返回值范围内是什么意思 (c++)?
- 函数范围的静态变量如何导致与共享库中函数代码的未来使用不兼容
- 成员变量在超出BeginPlay函数虚幻引擎的范围时丢失值c++
- 将自适应阈值应用于范围函数 opencv c++