gpt4 book ai didi

c++ - 类变量 : public access read-only, 但私有(private)访问读/写

转载 作者:IT老高 更新时间:2023-10-28 13:58:46 27 4
gpt4 key购买 nike

哎呀,暂时不在那个套接字库上工作。我正在尝试在 C++ 方面对自己进行更多的教育。

对于类,有没有办法使变量对公众只读,但在私有(private)访问时读+写?例如像这样:

class myClass {
private:
int x; // this could be any type, hypothetically

public:
void f() {
x = 10; // this is OK
}
}

int main() {
myClass temp;

// I want this, but with private: it's not allowed
cout << temp.x << endl;


// this is what I want:

// this to be allowed
temp.f(); // this sets x...

// this to be allowed
int myint = temp.x;

// this NOT to be allowed
temp.x = myint;
}

简而言之,我的问题是如何允许从 f() 内完全访问 x 但从其他任何地方进行只读访问,即 int newint = temp.x; 允许,但 temp.x = 5; 不允许?类似于 const 变量,但可从 f()...

写入

编辑:我忘了提到我打算返回一个大 vector 实例,使用 getX() 函数只会复制它,它并不是真正的最佳选择。我可以返回一个指向它的指针,但这是 iirc 的不好做法。

P.S.:如果我只是想基本上展示我的指针知识并询问它是否完整,我会在哪里发布?谢谢!

最佳答案

当然可以:

class MyClass
{
int x_;

public:
int x() const { return x_; }
};

如果您不想复制(对于整数,没有开销),请执行以下操作:

class MyClass
{
std::vector<double> v_;

public:
decltype(v)& v() const { return v_; }
};

或使用 C++98:

class MyClass
{
std::vector<double> v_;

public:
const std::vector<double>& v() const { return v_; }
};

这不会进行任何复制。它返回一个 reference to const .

关于c++ - 类变量 : public access read-only, 但私有(private)访问读/写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5424042/

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