C + + Class design 1 (class without pointer members)

Source: Internet
Author: User

Class complex{public    :        complex (Double r = 0, double i = 0): Re (r), Im (i) {}//inline        complex& operator + = { Const complex&};                  Double Real () Const{return re;}   Inline        double imag () Const{return im;}  Inline    private:        double re,im;        Friend complex& _doap1 (complex*, const complex); }; Inline double imag (const complex& x) {          //inline        return X.imag ();        }                

3. Access level

Private: Data part, encapsulated, not accessed by outside (class).

Public: can be accessed outside (class).

The definition is not necessarily focused on two paragraphs, you can use the two keywords alternately according to the actual situation.

4 Constructors (ctor)

Create object is called constructor, function name is the same as class name, no return value type.

The following three methods of creating objects call constructors

Class complex{public    :        complex (Double r = 0, double i = 0): Re (r), Im (i) {}//can take parameters, parameters can have default values, which is unspecified when using default values                                                             //Initialization of columns Table: Re (r), IM (i) can use        complex& operator + = {Const complex&};        when using initialization list Double Real () Const{return re;}        Double imag () Const{return im;}    Private:        double re,im;        Friend complex& _doap1 (complex*, const complex); }; {    complex C1 (2,1);            All three methods call the constructor    complex C2;    Complex *p = new complex (4);    ... }

4.2 Constructors in private zone

cannot be mobilized by the outside world, for example in singleton mode

Class A{public:    static a& getinstance ();  Static type variable    setup () {}private:    A ();       The constructor is in private area    A (const a& ths);    ...     }; a& a::getinstance () {    static a A;    return A; }a::getinstance (). Setup ();  Use the Getinstace () function of a class

5 Heavy Duty (overloading)

A function of the same name can exist and determine whether it can be overloaded to determine whether the compiler can differentiate between the two functions.

Double Real () const {return re;} void Real (double r) {re = r;}    Correctly overloads complex (double r= 0, double i = 0): Re (r), Im (i) {};complex (): Re (r), Im (i) {};  Error, compiler can not judge, such as: Complex C1; I don't know which one to call.

6 Const member functions

Note the position of the const in the const functions: After the function name, before the function body

Double Real () Const{return re;} Double imag () Const{return im;} Do not change the content of the data, you must add a const, otherwise it may cause errors, such as://External call to use the function: const complex C1;  Declares a constant object, a regular object cannot call a very member function, an error occurs

7 pass by value or pass by reference (to const)

The value of the pass will be expensive (the base type can pass the value) and the reference can be passed as far as possible (overhead is only 4bytes).

If you do not want to give each other permission to modify, use the Const keyword, such as const complex&, as a common form.

Class complex{public    :        complex (Double r = 0, double i = 0): Re (r), Im (i) {}   //pass by value         complex& op Erator + = {Const complex&};                Pass by reference        double Real () Const{return re;}        Double imag () Const{return im;}    Private:        double re,im;        Friend complex& _doap1 (complex*, const complex&);    

8 return by value or return by reference

Try to pass the reference, not the case reference after 8.1 and temporary variable chapters

complex& operator + = {Const Complex&};friend complex& __DOAPL (complex*, const complex&);

8.1 When can I return by reference

Function operations return results

1) You must create a new object within the function and cannot return reference, because when the function ends, the object dies and the reference to the ontology is no longer present.

2) When the returned result is an object that already exists, you can return the reference, common case this pointer

Inline COMPLEX&__DOAPL (complex* ths, const complex& r) {    Ths->re + = r.re;    Ths->im + = r.im;    return *ths;} Inline Complex&complex::operator + = (Const complex& r) {    return __DOAPL (this, r);}

8.2 Pass/return by reference syntax analysis

The receiver does not need to know the receiving end in what form to receive;

In the following example, the return pass is only required to pass the original value, and the recipient himself decides to receive the reference or accept the value (call copy construct).

Inline COMPLEX&__DOAPL (complex* ths, const complex& r) {    Ths->re + = r.re;    Ths->im + = r.im;    return *ths;                   }

9. Friend (Friend)

Friend complex& __DOAPL (complex*, const complex&), inline complex&_doap1 (complex* ths, const complex& R) {    Ths->re + = r.re;                       Free to obtain friend's private variable, but destroy encapsulated    Ths->im +=r.im;    return *ths;}

9.1 Each object (class) of the same class (objects) is friends with each other

Class Complex{public:    complex (Double r = 0, double i = 0): Re (r), Im (i) {    }    int func (const complex& param) { C3/>return param.re + param.im;    }                                     //directly take the param private variable, can be used in the same kind of objects between each other to explain private:    double Re, im;};

10. Operator overloading 1, member function (operator overloading)

Binary operators are regarded by the compiler as a form: (note is to look at the form, this can be used, but the parameter list of this cannot be written out) this points to the caller

The actual code is as follows:

Inline COMPLEX&__DOAPL (complex* ths, const complex& r) {    Ths->re + = r.re;    Ths->im + = r.im;    return *ths;}                               Inline Complex&complex::operator + = (const complex& r)              //operator + = may be used by programmers in C1 + = C2 + = C3 Form It is necessary to return the complex& type, not void, similar to overloaded cout return type {return    __DOAPL (this, R)}

11. Operator overloading 2 non-member functions (no this pointer)

Global function, no this pointer.

For example, this plural class, overloaded plus and minus symbols, there are complex and subtraction of real numbers, it is not appropriate to use member functions.

Inline Complexoperator + (const complex& x, const complex& y) {    return complex (real (x) + real (y),            imag ( x) + imag (y));                       Returns the temporary variable within the function (local object), which dies after the function ends, so you cannot use return by reference}inline Complexoperator + (const complex& x, double y) { C3/>return Complex (real (x) + y, imag (x));} Inline Complexoperator + (double x, const complex& y) {    return complex (x + real (y), imag (y));}

Stream operator Overloading:

#includeostream & operator << (ostream& os, const complex&) {     //two parameters << left and right, such as cout << C1; cout type is ostream,    return OS << ' (' << real (x) << ', '              << imag (x) << ') ';}

Complex class complete code and test code

Complex.h Complex_test

C + + Class design 1 (class without pointer members)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.