C++ 에서 상위 크래스로 부터 상속받은 하위 클래스에서 연산자재정의(Operator Overloading) 하는 방법을 알아보자.
난해한 분분이 아니지만 가끔 해당부분을 구현하려고 생각하면 막막 할때가 있다.
C++ 초급자에겐 무척 이해하기 어려울 지도 모르겠다.
예제 소스코드는 아주 짧지만 눈에 잘 보이지 않는 함점을 가지고 있다, 또한 Library 가 풍부하기 때문에 Operator Overloading을 직접 구현하는 경우는 잘 없기 때문에 익숙하지 않아서 막상 코딩을 하려면 막막하기만 하다.
class WRECT는 RECT 클래스를 변수로 가진다.(MFC에서 RECT는 사각형을 조작 하기 쉽도록 구현된 클래스이다)
WRECT에는 변수로 ID를 지정하고 있다.
클래스의 구현 목적은 윈도우창의 ID와 그에 해당하는 화면사각형의 크기를 임의로 조작 하고 관리하기 위해 고안된 것이다.
그리고 class CRectIDArray는 CArray를 상속 받아서 WRECT 클래스의 배열을 할당한다.
class CRectIDArray:public CArray<WRECT,WRECT> 를 보면 WRECT관련 배열을 할당하고 있음을 알 수 있다.
CArray는 동적 배열을 하당하고 쉽게 관리하는 기능을 가지고 있다.
그런데 여기서 조금 어려운 부분은 CArray가 Template Class를 사용하고 있으므로 익숙하지 않은 개발자에게 좀 어렵게 보인다.
class WRECT { public: WRECT() { ID=0; m_rect.left=0; m_rect.top=0; m_rect.right=0; m_rect.bottom=0; }; WRECT(WORD id) { ID=id; m_rect.left=0; m_rect.top=0; m_rect.right=0; m_rect.bottom=0; }; WRECT(WORD id,int x1,int y1,int x2,int y2) { ID=id; m_rect.left=x1; m_rect.top=y1; m_rect.right=x2; m_rect.bottom=y2; }; WORD ID; RECT m_rect; }; class CRectIDArray:public CArray<WRECT,WRECT> { public: CRectIDArray(){}; int Add(WORD id ) { return CArray<WRECT,WRECT>::Add( WRECT(id)); }; int Add(WORD id ,int x1,int y1,int x2,int y2) { return CArray<WRECT,WRECT>::Add( WRECT(id,x1,y1,x2,y2)); }; WORD& operator []( int nIndex ) { WRECT p_r=CArray<WRECT,WRECT>::operator[](nIndex ); return p_r.ID; }; WORD operator []( int nIndex ) const { WRECT p_r=CArray<WRECT,WRECT>::operator[](nIndex ); return p_r.ID; }; WORD GetAt(int nIndex)const { return operator[](nIndex ); }; WORD GetAt( int nIndex ,RECT& pRec) { WRECT p_r=CArray<WRECT,WRECT>::GetAt(nIndex); pRec =p_r.m_rect; return p_r.ID; }; };
자 하나씩 확인해보자
CArray Class Members 를 보면
Attributes
GetSize Gets the number of elements in this array.
GetUpperBound Returns the largest valid index.
SetSize Sets the number of elements to be contained in this array.
Operations
FreeExtra Frees all unused memory above the current upper bound
RemoveAll Removes all the elements from this array. .
…………………….
Operators operator [] Sets or gets the element at the specified index.
와 같이 구성되 있는데
1. 부모클래스 연산자를 상속된 자식클래스에서 재정의
WORD operator []( int nIndex ) const 와 같이 하위크래스에서 다시 정의 하였다.
함수코드 내부에서 부보클래스의 연산자를 호출하기 위해서는 “부모클래스::operator []( int nIndex )”와 같이 호출하면 된다. 그런데 상위클래스가 Template 클래스를 사용하고 있으므로 하위클래스의 코드구현 부분에서 WRECT p_r=CArray<WRECT,WRECT>::operator[](nIndex ); 와 같이 호출 해야 한다.
2. 연산자 중복
CRectIDArray의 코드를 보면 CArray<WRECT,WRECT> 를 상속 받고 WRECT와 관련된 어떠한 행동도 없다. 조금 이상하게 보이겠지만 여긴엔 연산자 중복의 개념이 숨어 있다.
operator []( int nIndex ) 는 CArray에도 있지만 상속된 CRectIDArray에도 있다, 그런데 두 클래스는 값을 반환하는 Type이 다르다.
TYPE& operator []( int nIndex );
WORD CRectIDArray::operator []( int nIndex ) const
WRECT CArray<WRECT,WRECT>::operator[](nIndex )
이는 연산자가 중복되어 있으므로
void main()
{
WRECT mW[2];
mW[0].ID=10;
mW[1].ID=100;
CRectIDArray mArr; ///WRECT 를 배열로 추가한다
mArr.Add(mW[0]);
mArr.Add(mW[0]);
mArr.Add(mW[1]);
mArr.Add(mW[1]);
mW[2];를 선언해서 WRECT 를 두개를 할당 했지만
mArr는 4개의 WRECT 가 추가되어 있다.
: int sz =mArr.GetSize(): 를 실행하면 sz는 4를 반한한다.
WORD id=mArr[0];//를 실행하면 WORD&CRectIDArray:: operator []( int nIndex ) 가 실행되어 id=10 이된다
WRECT wr=mArr[0];//를 실행하면 CArray<WRECT,WRECT>::operator[](nIndex )가 실행되어 wr에는 WREC가 할당된다.
}
핑백: Panzer Arms AR-12 PRO Shotgun AR Twelve PRO 12ga
핑백: giải mã giấc mơ thấy rắn hổ mang
핑백: Online Klundert Dating Club
핑백: mơ thấy xương người
핑백: mơ bị đứt tay
핑백: DevOps
핑백: Digital transformation consultants
핑백: mơ bị sét đánh
핑백: mơ thấy lợn đẻ
핑백: best quality best synthetic wigs under $59
핑백: 안전공원
핑백: what is web hosting
핑백: nằm mơ thấy mình thắp hương
핑백: nằm mơ thấy hoa sen
핑백: nằm mơ thấy ngựa đánh số gì
Hi to all, how is everything, I think every
one is getting more from this site, and your
views are nice in favor of new viewers.
You actually make it seem really easy along with your presentation but I to find this topic to be
really one thing which I feel I’d never understand. It seems too
complicated and very huge for me. I am having
a look ahead on your next put up, I’ll attempt to get the grasp of it!
Hello, I enjoy reading through your article post. I wanted to
write a little comment to support you.
Oh my goodness! Incredible article dude! Thank you so much, However I am experiencing difficulties with
your RSS. I don’t understand why I can’t join it. Is
there anybody getting identical RSS problems? Anyone that knows the answer can you kindly respond?
Thanks!!
Good content, Thahks a lot!
Best Essay writing
How to quotre tv shows https://servicethesis.com/write-a-research-paper-fast
Truly a lot of awesome info.
Best Essay writing
Buying essays plagiarism https://admissionessaywritingservice.com/?academic.writing.in.english
Excellent, what a website it is! This webpage presents valuable information to us, keep it up.
https://issues.joomla.org/tracker/joomla-cms/31763
my essay writer
my essay writer https://www.hasd.org/schools/foxwestacademy/Deadline.cfm?posts=1&threadid=3117
Kudos, Plenty of info.
Best Essay writing
geography essay https://researchingforpaper.net/high-school-essays/
I’m not positive the place you’re getting your info, however great topic.
I must spend a while studying more or working out more. Thanks for excellent information I used to
be searching for this info for my mission.
Hey are using WordPress for your blog platform? I’m new to
the blog world but I’m trying to get started and create
my own. Do you require any coding expertise to make your own blog?
Any help would be greatly appreciated!
Hey would you mind letting me know which hosting
company you’re utilizing? I’ve loaded your blog in 3 completely different
internet browsers and I must say this blog loads a lot quicker then most.
Can you recommend a good hosting provider at a honest price?
Thanks, I appreciate it!
Thanks for another excellent article. Where else may anybody get that kind of info in such a
perfect means of writing? I have a presentation next week,
and I am on the search for such information.
I am curious to find out what blog platform you have
been working with? I’m having some small security issues with my
latest blog and I’d like to find something more safe. Do you have any solutions?
Its such as you read my mind! You appear to know a lot approximately this,
such as you wrote the guide in it or something. I feel that
you could do with a few percent to power the message home a bit, but
other than that, that is excellent blog. A fantastic read.
I’ll definitely be back.
It?s nearly impossible to find educated people for this topic, but you seem like
you know what you?re talking about! Thanks
Also visit my web-site – Premium Health CBD Oil
Hi there! I could have sworn I’ve visited this blog before but after looking at a few of
the posts I realized it’s new to me. Nonetheless, I’m certainly happy I discovered it and I’ll be bookmarking it and checking back often!
my page: Isogenesis Keto Review
Great work! This is the type of information that are meant to be
shared across the internet. Shame on Google for not positioning this submit upper!
Come on over and consult with my website . Thank you =)
Appreciate the recommendation. Will try it out.
Link exchange is nothing else but it is just placing the other person’s weblog link on your page
at proper place and other person will also do similar in favor of you.
Review my web-site – idn slot
Good information. Lucky me I found your site by accident (stumbleupon).
I have saved as a favorite for later!
It’s actually very difficult in this busy life to listen news on Television,
thus I simply use internet for that reason, and obtain the most up-to-date
news.
Here is my webpage – judi sabung ayam online
핑백: online wig stores
Nicely put, Appreciate it!
essay helper
essay helper https://webcustomwritinghelp.com/
You actually stated that wonderfully!
writing service
essay writiung service https://searchwritingservicesc.com/
You actually suggested that wonderfully!
essay writer service
essay writer service https://websiteessaywriter.com/
You actually expressed this effectively.
Best Essay writing
Writing a why this college essay https://clubcustomessay.com/improve-your-essay-writing.html
You aactually suggested iit fantastically!
paper writing service
paper writing https://fastpaperwritingservice.com/
You actually reported this terrifically!
writing paper
writing paper https://qualitywritingpaper.com/
I like the valuable info you provide in your articles. I’ll bookmark your weblog and check again here regularly.
I am quite certain I’ll learn many new stuff right here!
Good luck for the next!
Thank you, I’ve just been searching for info approximately this topic for ages and yours is the best I’ve discovered so far.
However, what about the conclusion? Are you certain in regards
to the source?
https://allbestessaywritingservice.com
buy cusetom essay
buy custom essay
https://allbestessaywritingservice.com https://allbestessaywritingservice.com
Good info. Lucky me I recently found your blog by chance
(stumbleupon). I’ve book marked it for later!
Look at my site … poker deposit pulsa tanpa potongan
핑백: cc cvv shop
Hi! This post could not be written any better! Reading this
post reminds me of my previous room mate! He always kept talking about this.
I will forward this page to him. Fairly certain he will have a good read.
Many thanks for sharing!
my webpage: poker pakai pulsa
Just desire to say your article is as surprising.
The clarity in your post is just cool and i could assume you’re an expert on this subject.
Well with your permission allow me to grab your RSS
feed to keep updated with forthcoming post. Thanks
a million and please keep up the gratifying work.
Also visit my homepage: poker online depo pulsa
I do not know if it’s just me or if perhaps everybody
else experiencing issues with your site. It seems like some of the text within your content
are running off the screen. Can someone else please comment and let me know if this
is happening to them as well? This may be a issue with my internet
browser because I’ve had this happen before.
Cheers
My blog :: s128 login
Asking questions are genuinely good thing if you are not understanding anything entirely, however this piece of writing offers fastidious
understanding yet.
online dating free,free dating online
set free dating sites
[url=”http://datingfreetns.com/?”]free dating sites[/url]
I’m honored to obtain a call from a friend immediately he
observed the important points shared on the site. Reading through your blog article is a real fantastic experience.
Thank you for thinking about readers just like me, and I want for you the best of achievements for a professional in this
area.
Also visit my website: carquest mn locations
I could not refrain from commenting. Exceptionally well
written!
Right away I am ready to do my breakfast, once having my breakfast
coming yet again to read more news.
Veery shortly this web pazge will be famous
among us mod ips all blogging and
site-building people, due too it’s pleasant articles
or reviews
Thanks in favor of sharing such a nice thought,
article is pleasant, thats why i have read it entirely
I think this is among the most important info for me. And i’m glad reading your article.
But want to remark on few general things, The site style
is perfect, the articles is really nice : D. Good job, cheers
Wow, that’s what I was seeking for, what a data! existing here at this web site,
thanks admin of this web page.
Wow, awesome blog layout! How long have you been blogging for?
you made blogging look easy. The overall look of your site is great, as well as the
content!
Hello there! Do you know if they make any plugins to
protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?
Can you tell us more about this? I’d care to find out mre details.
https://colleen84.mypixieset.com/narrative-essay-examples/
write an essay
write an essay https://cornyp60kntr.medium.com/should-i-download-my-college-essay-through-a-pdf-or-word-doc-801375986664
Hi there colleagues, how is the whole thing, and what you desire
to say on the topic of this post, in my view its really amazing in favor of me.
how to use tinder , tinder dating app https://tinderdatingsiteus.com/
Good post. I will be goung through many of these issues as well..
https://clients1.google.jo/url?q=https://kratomwwwtea.com
Earlene
Adeline https://clients1.google.li/url?q=https://kratomwwwtea.com
Your style is so unique compared to other people I have read stuff from.
I appreciate you for posting when you’ve got the opportunity, Guess I will just
book mark this blog.
Here is my web blog: bookep
I know this if off topic but I’m looking into starting my own weblog and was wondering what all is
needed to get setup? I’m assuming having a blog like yours would cost a pretty penny?
I’m not very internet smart so I’m not 100% sure. Any tips or advice
would be greatly appreciated. Thanks
my web page – link alternatif s128
That is really fascinating, You are an excessively skilled blogger.
I have joined your feed and sit up for searching for
more of your wonderful post. Also, I have shared your web site in my social networks
Also visit my web-site; slot pulsa online
Wonderful beat ! I would like to apprentice while you amend your website, how can i subscribe for a
blog website? The account aided me a acceptable deal.
I had been tiny bit acquainted of this your broadcast provided bright clear concept
my blog post: login slot online
I have been browsing link poker online more than three hours these days, yet I by no
means found any interesting article like yours.
It’s beautiful worth sufficient for me. Personally,
if all web owners and bloggers made just right content material as you did, the internet might be a lot more helpful than ever before.
Hey! I know this is somewhat off topic but I was
wondering which blog platform are you using for this website?
I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking at options
for another platform. I would be great if you could point me in the direction of a good platform.
Also visit my web-site idn poker online
Wow, that’s what I was seeking for, what a stuff!
present here at this website, thanks admin of this site.
Here is my website: agen s128
I think everything published was very logical. But, consider this, what if you composed a catchier title?
I am not suggesting your information is not solid,
however what if you added a headline to possibly grab folk’s attention? I mean 상속된 템플릿 클래스의 연산자 오버로딩(Operator Overloading) | 기록은 자산 is kinda plain. You
ought to glance at Yahoo’s front page and watch how they create news headlines to
get viewers to open the links. You might add a video or a related pic or two to get people excited about what you’ve written. Just my opinion, it
might bring your website a little bit more
interesting.
Feel free to surf to my web blog – idn live deposit pulsa
I feel that is one of the such a lot vital information for
me. And i am glad studying your article. But wanna
remark on few basic issues, The website style is wonderful, the articles is truly great :
D. Excellent task, cheers
My website – bandar sabung ayam online
Howdy! This post could not be written any better! Going
through this article reminds me of my previous roommate! He continually kept preaching about this.
I most certainly will send this information to him. Pretty sure
he’s going to have a great read. Many thanks for sharing!