less than 1 minute read

🏫Chapters 9 : Class

📖Operator Overloading

모든 사람들이 친숙하게 알고 있는 +, -, [], <<, >>등 에 대한 연산자를 사용자 정의 타입에도 지원할 수 있게 하자는 것

  • overloading : 이름은 같지만, 파라미터의 타입과 개수가 다른 정의를 가지고 있는 것
    overriding : 이름과 파라미터의 타입과 개수가 같지만, 유도클래스에서 재정의할 수 있는 것

  • Ex

    class Negative{};
    class Sample{
        private:
            int m;  
            int n;
            void setM(int x, int y);

        public: 
            void Sample();
            void Sample(int i);
            void Sample(const Sample &a);
            void ~Sample();
            void setM(int x);
            int getM() const;
            Sample operator+(Sample &a);    
    };

    Sample Sample::operator+(Sample &a){
        Sample x;
        x.m = this->m + a.m;
        x.n = this->n + a.n;

        return x;
    }
  • 다형성을 지원하는 한 가지 방법 중 하나