【发布时间】:2011-07-22 09:30:22
【问题描述】:
哎呀,暂时不在那个套接字库上工作。我正在尝试在 C++ 方面对自己进行更多的教育。
对于类,有没有办法使变量对公众只读,但在私有访问时读+写?例如像这样:
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() 写入...
编辑:我忘了提到我打算返回一个大向量实例,使用 getX() 函数只会复制它,它并不是真正的最佳选择。我可以返回一个指向它的指针,但这是 iirc 的不好做法。
P.S.:如果我只是想基本上展示我的指针知识并询问它是否完整,我会在哪里发布?谢谢!
【问题讨论】:
标签: c++ access-modifiers