哇塞,暂时还没有在那个套接字库上工作。我正在尝试让自己多学一点 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,但是从其他任何地方只读访问 x,即允许 int newint = temp.x;,但是不允许 temp.x = 5;?类似于常量变量,但是可以从 f()写入..。
编辑: 我忘了提到我计划返回一个大的向量实例,使用 getX ()函数只会产生一个副本,而且它并不是真正最优的。我可以返回一个指针指向它,但这是不好的练习 iirc。
附注: 如果我只是想展示我对指针的基本知识,并询问它是否完整,那么我应该在哪里发帖呢?谢谢!