gpt4 book ai didi

c++ - 通过引用或指针声明属性 C++

转载 作者:太空宇宙 更新时间:2023-11-04 15:04:01 25 4
gpt4 key购买 nike

我想声明一个类的一些属性。我正在考虑为我在类里面想要的属性创建私有(private)变量。

然后通过引用公开私有(private)变量。但是我有指针也可以传递私有(private)变量的地址。因此类的用户可以修改变量。

那么通过引用或指针哪种方式会更好,如下面的示例所示?

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;
}


}

最佳答案

最好什么都不做:

  public:
int GetAge() { return age; }
void SetAge(int age) { this->age = age; }

通过这种方式,您可以添加健全性检查,例如年龄不为负数,并更改底层实现而无需更改该类的所有用户。

关于c++ - 通过引用或指针声明属性 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21486714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com