类变量:公共访问只读,但私有访问读/写 [英] Class variables: public access read-only, but private access read/write

查看:153
本文介绍了类变量:公共访问只读,但私有访问读/写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Whoopee,暂时不在那个套接字库上工作。我试图在C ++中教育自己一点点。

Whoopee, not working on that socket library for the moment. I'm trying to educate myself a little more in C++.

有了一个方法,使一个变量只读的公共,但读+写当私人访问?例如像这样:

With classes, is there a way to make a variable read-only to the public, but read+write when accessed privately? e.g. something like this:

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

我的问题,精简是如何允许完全访问<$ c $从 f()内,但是从任何其他地方只读访问,即 int newint = temp.x ; 允许,但 temp.x = 5; 不允许?像一个常量变量,但可写从 f() ...

My question, condensed, is how to allow full access to x from within f() but read-only access from anywhere else, i.e. int newint = temp.x; allowed, but temp.x = 5; not allowed? like a const variable, but writable from f()...

编辑:我忘了提及计划返回一个大的向量实例,使用一个getX()函数只会做一个副本,它不是真正的最佳。我可以返回一个指针,但这是坏的做法iirc。

I forgot to mention that I plan to be returning a large vector instance, using a getX() function would only make a copy of that and it isn't really optimal. I could return a pointer to it, but that's bad practice iirc.

PS:如果我只想基本上显示我的知识的指针,完成还是不完成?谢谢!

P.S.: Where would I post if I just want to basically show my knowledge of pointers and ask if it's complete or not? Thanks!

推荐答案

当然可以:

class MyClass
{
    int x_;

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

如果你不想复制一个(对于整数,没有开销)如下:

If you don't want to make a copy (for integers, there is no overhead), do the following:

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

public:
    const std::vector<double>& x() const { return x_; }
};

这不会产生任何副本。它返回 对const 的引用

This does not make any copy. It returns a reference to const.

这篇关于类变量:公共访问只读,但私有访问读/写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆