tec*_*fun 0 c++ pointers reference
我想声明一个类的一些属性.我正在考虑为类中我想要的属性创建私有变量.
然后通过引用公开私有变量.但是我通过指针也可以传递私有变量的地址.因此,类的用户可以修改变量.
那么哪种方式通过引用或指针会更好,如下例所示?
class ExampleClass
{
private:
int age;
public:
//This function allows access via reference
int& GetAgeByReference()
{
int& refAge= age;
return refAge;
}
//This function allows access via pointer
int* GetAgeByPointer()
{
int* pointAge= &age;
return pointAge;
}
}
Run Code Online (Sandbox Code Playgroud)
最好不要做:
public:
int GetAge() { return age; }
void SetAge(int age) { this->age = age; }
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以添加健全性检查,例如年龄不是负面的,并且无需更改类的所有用户即可更改基础实现.