[英]How do I access a variable in member function #1 in member function #2?
I'm starting to work with friends of classes. 我开始和班级的朋友一起工作。 Here I have two functions called setMaxSickDays and getMaxSickDays.
这里我有两个函数叫做setMaxSickDays和getMaxSickDays。 I made a variable called maxSickDays in setMaxSickDays that I'd like to access from getMaxSickDays.
我在setMaxSickDays中创建了一个名为maxSickDays的变量,我想从getMaxSickDays访问它。
class timeOff
{
public:
void setMaxSickDays(numDays &friendlyObject) {
int maxSickDays;
friendlyObject.hours = 240;
maxSickDays = friendlyObject.hours;
}
void getMaxSickDays(numDays &friendlyObject) {
cout << maxSickDays;
}
};
The error: 'maxSickDays' was not declared in this scope 错误:'maxSickDays'未在此范围内声明
This may seem silly but I'm a beginner. 这可能看起来很傻,但我是初学者。 Thanks!
谢谢!
You make maxSickDays
a data member of your class. 您将
maxSickDays
作为您班级的数据成员。
class timeOff
{
public:
void setMaxSickDays(int days);
int getMaxSickDays();
private:
int maxSickDays;
};
You can't access another function's local variable, even as friend
. 即使是
friend
,也无法访问其他函数的局部变量。 friend
is used to granted to access members (ie member variables or functions) of the class. friend
用于授予访问类的成员(即成员变量或函数)。
See friend declaration 见朋友声明
The friend declaration appears in a class body and grants a function or another class access to private and protected members of the class where the friend declaration appears.
友元声明出现在类主体中,并授予一个函数或另一个类访问友元声明出现的类的私有和受保护成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.