• [C++] Class (part 2)


    Members that are const or reference must be initialized. Similary, members that are of a class type that does not define a default constructor also must be initialized.

    class ConstRef{
    public:
        ConstRef(int ii);
    private:
        int i;
        const int ci;
        int & ri;
    };
    
    ConstRef::ConstRef(int ii){
        i = ii;    // ok
        ci = ii;    // error: cannot assign to a const
        ri = i;     // error: ri was never initialized
    }

    By the time the constructor begin executing, initialization is completed. The correct way to wirtie this constructor is:

    // explictly initialize reference and const members
    ConstRef::ConstRef(int ii): i(ii), ci(ii), ri(i) { }

    Members are initiazlied in the order in which they appear in the class definition, not the order in which they appear in the constructor initializer.

    class X{
        int i;
        int j;
    public:
        // undefined: i is initialized before j
        X(int val): j(val), i(j) { }
    }

    To avoid using members to initiazlie other members.

        X(int val): j(val), i(val) { }
    class Sales_data{
    public:
        // non-delegating constructor initialize member before corresponding argument
        Sales_data(string s, unsigned cnt, double price): bookNo(s), units_sold(cnt), revenue(cnt * price) { }
    
        // remaining constructors all delegate to another constructor
        Sales_data(): Sales_data('', 0, 0) { }
        Sales_data(string s): Sales_data(s, 0, 0){ }
        Sales_data(istream & is): Sales_data() { read(is, *this); }
    };

    Had the function bodies contain code, that code would be run before control return to the function body of the delegating constructor.

    In practice, it is almost right to provide a default constructor if other constructor is defined.

    class NoDefault{
    public:
        NoDefault( const string &);
        // additional members follow, but no other constructor
    };
    
    Struct A{
        NoDefault my_mem;
    };
    
    A a;    // error: cannot synthesize a constructor of A
    
    Struct B{
        B() { }    // error: no initialization for b_member
        Default b_member;
    };

    It is common mistake among programmers new to C++ to try to declare  an object initialized with the default constructor as function

        // opps! defines a function taking no parameter and returning an object of type Sales_data
        Sales_data obj();
    
        // define an object that use the default constructor
        Sales_data obj;

    Reference:

    C++ Primer, Fifth Edition, chapter 7 Classes

  • 相关阅读:
    WebService 安静点
    爬虫(一) 安静点
    wpf(三) 安静点
    wpf问题解决链接 安静点
    wpf(一) 安静点
    webapi(一) 安静点
    WPF(二)之为对象属性赋值 安静点
    wpf(四) 安静点
    云计算实验二 Docker实验docker安装
    新闻分类中文分词+词云展示(2)
  • 原文地址:https://www.cnblogs.com/TonyYPZhang/p/6551603.html
Copyright © 2020-2023  润新知