C++ Primer 读书笔记 - 第十四章

    添加时间:2013-6-2 点击量:

    1. An overloaded operator must have at least one operand of class or enumeration type.


    2. Default arguments for overloaded operators are illegal, except for operator(), the function-call operator.


    3. The assignment (=), subscript ([]), call (()), and member access arrow (->) operators must be defined as members. Defining any of these operators as a nonmember function is flagged at compile time as an error.


        Like assignment, the compound-assignment operators ordinarily ought to be members of the class. Unlike assignment, they are not required to be so and the compiler will not complain if a nonmember compound-assignment operator is defined.


        Other operators that change he state of their object or that are closely tied to their given type - such as increment, decrement, and dereference - usually should be members of the class.


        Symmetric operators, such as the arithmetic, equality, relational, and bitwise operators, are best defined as ordinary nonmember functions.


    4. < 和 == 的定义应当对峙一致。


    5. 定义下标操纵的类,应当有两个版本:返回引用的非const成员,返回const引用的const成员。


    6. 不消为ScreenPtr类定义默认机关函数,是以,一个ScreenPtr对象将老是指向一个Screen对象,不会有未绑定的ScreenPtr,这一点和内置指针不合。


    6. Function Object



    class GT_cls {
    
    public:
    GT_cls(size_t val
    = 0) : bound(val) { }
    bool operator() (const string &s) { return s.size() >= bound; }
    private:
    std::
    string::size_type bound;
    };

    count_if(words.begin(), words.end(), GT_cls(
    6));

    count_if的原型是
    template
    <class InputIterator, class UnaryPredicate>
    typename iterator_traits
    <InputIterator>::difference_type
    count (InputIterator first, InputIterator last, UnaryPredicate pred)
    {
    typename iterator_traits
    <InputIterator>::difference_type ret = 0;
    while (first!=last) {
    if (pred(first)) ++ret;
    ++first;
    }
    return ret;
    }

    因为类重载了()操纵符,所以pred(
    first)仍然可用。




    文艺不是炫耀,不是花哨空洞的文字堆砌,不是一张又一张的逆光照片,不是将旅行的意义转化为名牌包和明信片的物质展示;很多时候它甚至完全不美——它嘶吼、扭曲,它会痛苦地抽搐,它常常无言地沉默。——艾小柯《文艺是一种信仰》
    分享到: