[Original] Metamorphosis of C ++ operator overload - characteristic focusing subclass conversion

xiaoxiao2021-03-06  41

Hey, if the member variable of the class is a specific class and a custom structure, using this class name or structure as an operator.

(Of course, the basic type is also, but the practicality is not strong, only the code readability is reduced.)

As described below, a CPERSON, forcibly converting to HAND, or can be used.

Similar to reality, we will only express a strong interest in the specific characteristics of a substrate, which means characteristic. If the HR department will only pay attention to a candidate's Skill.

Of course, in practice, excessive use of this subclass conversion will only reduce the code readability.

In addition, there are multiple kinds of members in the class, such a conversion makes people inexplicably.

Instance code:

// Person.h: interface for the cperson class.////

#if! defined (AFX_PERSON_H__A825C71F_CB10_4997_8F9C_DBE792C5C387__included _) # Define AFX_PERSON_H__A825C71F_CB10_4997_8F9C_DBE792C5C387__included_

#if _MSC_VER> 1000 # prgma overce # endif //_MSC_VER> 1000

Typedef struct tag_hand {bool bsix; bool blefty;

Class cskill {public: cskill (): strdesc (null) {} Virtual ~ cskill () {}

PUBLIC: CHAR * STRDESC;};

Class CPERSON {public: cPerson (); Virtual ~ CPERSON (); hand m_hand; cskill m_skill;

Operator hand () const; operator cskill () const;

STATIC void test ();

#ENDIF /! Defined (AFX_PERSON_H__A825C71F_CB10_4997_8F9C_DBE792C5C387__included_)

// Person.cpp: importation of the cperson class.////

#include "stdafx.h" #include "person.h"

//// construction / destruction //

CPERSON :: CPERSON () {}

CPERSON :: ~ cPerson () {}

CPERSON :: Operator hand () const {return m_hand;}

CPERSON :: Operator cskill () const {return m_skill;}

Void CPERSON :: Test () {CPERSON PERSON; PERSON.M_HAND.BSIX = false; person.m_hand.blefty = true;

Person.m_skill.strdesc = new char [1024]; strcpy (person.m_skill.strdesc, "good at programming ...");

Printf ("% D,% D / N", ((HAND) Person) .BSIX, ((HAND) Person) .blefty); Printf ("% S / N", ((cskill) Person .strdesc);

DELETE [] Person.m_skill.strdesc; return;}

INT main (int Argc, char * argv []) {cPerson :: test (); return 0;}

Output:

转载请注明原文地址:https://www.9cbs.com/read-51416.html

New Post(0)