相关疑难解决方法(0)

类变量:公共访问只读,但私有访问读/写

哎呀,暂时不在那个套接字库上工作.我正在尝试用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 …
Run Code Online (Sandbox Code Playgroud)

c++ access-modifiers

52
推荐指数
4
解决办法
4万
查看次数

标签 统计

access-modifiers ×1

c++ ×1