Class variables: public access read-only, but private access read/write

后端 未结 12 647
感动是毒
感动是毒 2020-11-28 05:25

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-

12条回答
  •  温柔的废话
    2020-11-28 06:08

    Of course you can:

    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 v_;
    
    public:
        decltype(v)& v() const { return v_; }
    };
    

    or with C++98:

    class MyClass
    {
        std::vector v_;
    
    public:
        const std::vector& v() const { return v_; }
    };
    

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

提交回复
热议问题