面试题答案
一键面试在C++中,虽然私有成员变量不能直接在类外部访问,但可以通过类提供的公共成员函数(如getter和setter)来间接访问。
- getter函数:用于获取私有成员变量的值。
- setter函数:用于设置私有成员变量的值。
以下是代码示例:
#include <iostream>
class MyClass {
private:
int privateVariable;
public:
// 构造函数,初始化私有成员变量
MyClass(int value) : privateVariable(value) {}
// getter函数
int getPrivateVariable() const {
return privateVariable;
}
// setter函数
void setPrivateVariable(int value) {
privateVariable = value;
}
};
int main() {
MyClass obj(10);
// 通过getter函数获取私有成员变量的值
std::cout << "The value of private variable is: " << obj.getPrivateVariable() << std::endl;
// 通过setter函数设置私有成员变量的值
obj.setPrivateVariable(20);
std::cout << "After setting, the value of private variable is: " << obj.getPrivateVariable() << std::endl;
return 0;
}
在上述代码中:
MyClass
类包含一个私有成员变量privateVariable
。getPrivateVariable
函数是一个getter函数,用于返回privateVariable
的值。setPrivateVariable
函数是一个setter函数,用于设置privateVariable
的值。- 在
main
函数中,通过调用getPrivateVariable
和setPrivateVariable
函数来间接访问和修改私有成员变量。