代码之家  ›  专栏  ›  技术社区  ›  Michael

优雅的解决方案来复制,常量和非常量,getter?[副本]

  •  156
  • Michael  · 技术社区  · 17 年前

    class Foobar {
    public:
        Something& getSomething(int index) {
            // big, non-trivial chunk of code...
            return something;
        }
    
        const Something& getSomething(int index) const {
            // big, non-trivial chunk of code...
            return something;
        }
    }
    

    我们不能用另一个方法实现这两个方法中的任何一个,因为你不能调用非- const 需要一名演员来呼叫 版本从非- 一个。

    8 回复  |  直到 13 年前
        1
  •  96
  •   Silicomancer    7 年前

    它不是特别漂亮,但很安全。由于调用它的成员函数是非const的,因此对象本身也不是const,并且允许丢弃const。

    class Foo
    {
    public:
        const int& get() const
        {
            //non-trivial work
            return foo;
        }
    
        int& get()
        {
            return const_cast<int&>(const_cast<const Foo*>(this)->get());
        }
    };
    
        2
  •  26
  •   Steve Jessop    17 年前

    template<typename IN, typename OUT>
    OUT BigChunk(IN self, int index) {
        // big, non-trivial chunk of code...
        return something;
    }
    
    struct FooBar {
        Something &getSomething(int index) {
            return BigChunk<FooBar*, Something&>(this,index);
        }
    
        const Something &getSomething(int index) const {
            return BigChunk<const FooBar*, const Something&>(this,index);
        }
    };
    

    BigChunk可能需要尊重自己,在这种情况下,上述定义顺序不会很好地工作,需要一些前向声明来解决这个问题。

        3
  •  7
  •   Matthew Flaschen    17 年前

    我会将const转换为非const(第二种选择)。

        4
  •  6
  •   Jay    17 年前

    const 作为参考,你最好把会员公开。

    我相信这是Scott Meyers(高效C++)。

        5
  •  5
  •   markh44    17 年前

    试着通过重构代码来消除getter。如果只有极少数其他东西需要Something,请使用朋友函数或类。

    一般来说,Getter和Setter会破坏封装,因为数据是公开的。使用friend只会将数据暴露给少数人,因此可以提供更好的封装。

        6
  •  3
  •   swongu    17 年前

        7
  •  3
  •   Abhay    9 年前

    “const”的概念是有原因的。对我来说,它建立了一个非常重要的合同,程序的进一步指令就是基于这个合同编写的。但你可以做以下几点:-

    1. 使您的成员“可变”
    2. 将'getters'设置为const

    有了这个,如果你需要维护使用getter的const功能以及非const用法(危险),可以在LHS上使用const引用。但是现在程序员有责任维护类不变量。

    我在一些团队中看到的另一个编码指南是:-

    • 允许从const成员函数引用。

    这使得整个代码库具有一定的一致性,调用者可以清楚地看到哪些调用可以修改成员变量。

        8
  •  -2
  •   Matthew    16 年前

    #define ConstFunc(type_and_name, params, body) \
        const type_and_name params const body \
        type_and_name params body
    
    class Something
    {
    };
    
    class Foobar {
    private:
        Something something;
    
    public:
        #define getSomethingParams \
        ( \
            int index \
        )
    
        #define getSomethingBody \
        { \
            return something; \
        }
    
        ConstFunc(Something & getSomething, getSomethingParams, getSomethingBody)
    };
    
    推荐文章