C + + programming pointers to members and basic guidelines for this pointer _c language

Source: Internet
Author: User
Tags modifier modifiers strlen volatile

Pointer to member
the declaration of a pointer to a member is a special case of a pointer declaration. Use the following sequence to declare them:

[Storage-class-specifiers] [Cv-qualifiers] type-specifiers [Ms-modifier]
qualified-name::* [cv-qualifiers] identifier
[= & Qualified-name:: Member-name];

Declaration specifier:

    • Optional storage class Descriptor.
    • Optional const and/or volatile specifiers.
    • Type descriptor: The name of the type. This is the type of member to point to, not the class.

Declaration character:

    • An optional Microsoft-specific modifier.
    • The qualified name of the class that contains the member to point to.
    • :: operator.
    • * operator.
    • Optional const and/or volatile specifiers.
    • An identifier that names a pointer to a member.

Optional initializer:

    • = operator.
    • & operator.
    • The qualified name of the class.
    • :: operator.
    • The name of the Non-static member of the class of the appropriate type.

As usual, multiple declarations (and any associated initializers) are allowed in a single declaration.
A pointer to a member of a class differs from a normal pointer because it has the type information of the type of the member and the type information of the class to which the member belongs. A regular pointer identifies only one object in memory or has only its address. A pointer to a member of a class identifies that member in all instances of the class. The following example declares a class, Window, and some pointers to member data.

Pointers_to_members1.cpp
Class window
{public
:
 window ();        Default constructor.
 Window (int x1, int y1,     //constructor specifying
 int x2, int y2);      Window size.
BOOL Setcaption (const char *sztitle); Set Window caption.
 const char *getcaption ();    Get window caption.
 char *szwincaption;      Window caption.
};

Declare A pointer to the data member Szwincaption.
char * Window::* pwcaption = &Window::szWinCaption;
int main ()
{
}

In the previous example, Pwcaption is a pointer to any member of a class that has a windowchar* type. Type pwcaption is not a char * Window::*. The next code fragment declares the pointer as a setcaption and getcaption member function.

const char * (Window::* PFNWGC) () = &Window::GetCaption;
BOOL (Window::* pfnwsc) (const char *) = &Window::SetCaption;

Pointers PFNWGC and Pfnwsc point to the Setcaption and windows of the Getcaption class, respectively. The following code copies the information to the window title directly using a pointer to the member Pwcaption:

Window Wmainwindow;
Window *pwchildwindow = new window;
Char *szuntitled = "Untitled-";
int cuntitledlen = strlen (szuntitled);

strcpy_s (Wmainwindow.*pwcaption, Cuntitledlen, szuntitled);
(wmainwindow.*pwcaption) [CUntitledLen-1] = ' 1 ';  Same as
//wmainwindow.szwincaption [cUntitledLen-1] = ' 1 ';
strcpy_s (Pwchildwindow->*pwcaption, Cuntitledlen, szuntitled); 
(pwchildwindow->*pwcaption) [CUntitledLen-1] = ' 2 '; Same as//pwchildwindow->szwincaption[cuntitledlen-1] = ' 2 ';

The difference between the. * and the –>* operator (the pointer operator to a member) is that the. * operator selects the object or object reference given by the member, whereas the –>* operator selects the member by pointer. (For more information about these operators, see Using an expression that refers to a pointer operator to a member.) )
The result of the pointer operator to the member is the type of the member-in this case, char *.
The following code fragment calls member functions Getcaption and setcaption using pointers to members:

Allocate a buffer.
enum {
 sizeOfBuffer =%
};
Char Szcaptionbase[sizeofbuffer];

Copy the main window caption into the buffer
//and append "[View 1]".
strcpy_s (Szcaptionbase, sizeOfBuffer, (WMAINWINDOW.*PFNWGC));
strcat_s (Szcaptionbase, sizeOfBuffer, "[View 1]");
Set the child window ' s caption.
(PWCHILDWINDOW->*PFNWSC) (szcaptionbase);

Restrictions on pointers to members
the address of a static member is not a pointer to a member. It is a general pointer to an instance of a static member. Because there is only one static member instance for all objects of a given class, you can use the normal address-of (&) and dereference (*) operators.
pointers to members and virtual functions
calling a virtual function by a pointer to a member function is like calling a function directly; the correct function is found and called in the V table.
All along, the key to virtual function work is to call them by pointing to a pointer to the base class. (For more information about virtual functions, see Virtual functions.) )
The following code shows how to call a virtual function by pointing to a pointer to a member function:

Virtual_functions.cpp
//compile with:/EHsc
#include <iostream>
using namespace std;

Class Base
{public
:
virtual void Print ();
};
void (Base::* bfnprint) () = &base:: Print;
void Base:: print ()
{
cout << "Print function for class base\n";
}

Class Derived:public Base
{public
:
void print ();//The print is still a virtual function.
};

void Derived:: print ()
{
cout << "Print function for class derived\n";
}

int main ()
{
 Base *bptr;
 Base Bobject;
Derived Dobject;
Bptr = &bObject; Set pointer to address of bobject.
(Bptr->*bfnprint) ();
Bptr = &dObject; Set pointer to address of Dobject.
(Bptr->*bfnprint) ();
}

Output:print function for class Base
Print function for class Derived

This pointer
The This pointer is a pointer that can only be accessed in a Non-static member function of class, struct, or union type. It points to the object for which the member function is invoked. Static member functions do not have this pointer.
Grammar

  This 
this->member-identifier

Note
The this pointer for the object is not part of the object; It is not reflected in the result of the sizeof statement on the object. Conversely, when a non-static member function is invoked on an object, the address of the object is passed to the function as a hidden parameter by the compiler. For example, the following function calls:

Mydate.setmonth (3);

Can be explained in the following ways:

Setmonth (&mydate, 3);

The address of an object can be provided from within the member function as the this pointer. Most of this use is implicit. It is legal to use this explicitly when referencing a member of a class, but it is not necessary. For example:

void Date::setmonth (int mn)
{
 month = MN;   These three statements
 this->month = MN;  are equivalent
 (*this). Month = MN;

An expression *this is typically used to return the current object from a member function:

return *this;

This pointer is also used to prevent self references:

if (&object!= this) {
//Don't execute in cases of self-reference

Attention
This assignment is not allowed because the this pointer cannot be changed. Early implementations of C + + allow this to be assigned to this value.
This pointer can sometimes be used directly-for example, when manipulating a self referencing data structure that requires the address of the current object.

This_pointer.cpp//compile with:/EHsc #include <iostream> #include <string.h> using namespace std;
 Class Buf {public:buf (char* szbuffer, size_t sizeofbuffer);
 buf& operator= (const BUF &);

void Display () {cout << buffer << Endl;}
 private:char* buffer;
size_t sizeOfBuffer;

}; Buf::buf (char* szbuffer, size_t sizeofbuffer) {sizeofbuffer++;//account for a NULL terminator buffer = new char[s
 Izeofbuffer];
  if (buffer) {strcpy_s (buffer, sizeofbuffer, szbuffer);
 sizeOfBuffer = sizeOfBuffer; } buf& buf::operator= (const BUF &otherbuf) {if (&otherbuf!= this) {if (buffer) Delete [] Buf

  Fer 
  sizeOfBuffer = strlen (otherbuf.buffer) + 1;
  Buffer = new Char[sizeofbuffer];
 strcpy_s (buffer, sizeofbuffer, otherbuf.buffer);
return *this;
 int main () {Buf mybuf ("My Buffer", 10);

 Buf yourbuf ("Your buffer", 12);

 Display ' My buffer ' mybuf.display (); Assignment Opperator MYbuf = Yourbuf;
Display ' Your buffer ' mybuf.display ();

 }

Output:

My buffer
your buffer

The type of this pointer
the const and keywords allow you to modify the type of the volatilethis pointer in the function declaration. To declare a function as an attribute with one or more keywords, add the keyword to the back of the function argument list.
Take a look at the following example:

Type_of_this_pointer1.cpp
class point
{
 unsigned X () const;
int main ()
{
}

The above code declares a member function X, where the this pointer is treated as a const pointer to a const object. You can use a combination of the cv-mod-list options, but they always modify the object pointed to by this, not the this pointer itself. Therefore, the following declaration declares that the function X;this pointer is a const pointer to a const object:

Type_of_this_pointer2.cpp
class point
{
 unsigned X () const;
int main ()
{
}

The type of this pointer in a member function is described by the following syntax, where Cv-qualifier-list is determined from the member function declaration, can be const and/or volatile, and Class-type is the name of the class:

[Cv-qualifier-list] Class-type * const this

In other words, this is always a const pointer and cannot be reassigned. The const or volatile qualifier used in a member function declaration applies to the class instance that is pointed to by this in the scope of the function.
The following table describes more information about how these modifiers work.
The semantics of the This modifier

Modifiers Meaning
Const Cannot change data member; Cannot call a member function that is not a const.
Volatile Each time the member data is accessed, the data is loaded from memory, and some optimizations are disabled.

It is an error to pass a const object to a member function that is not a const. Similarly, it is wrong to pass a volatile object to a member function that is not a volatile.
A member function declared as const cannot change a data member-in such a function, the this pointer is a pointer to a const object.
Attention
Constructors and destructors cannot be declared as const or volatile. However, they can be invoked on a const or volatile object.

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.