Thread: overloading Modulus

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    2

    overloading Modulus

    anyways i been trying to find somewhere on the internet that can help me overload %= and % operators.

    any help would be much thanked

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Just use "operator%"..you can then overload it for what types you want to use modulus with....like so


    Code:
    #include <iostream>
    
    class MyClass{
    public:
    	void Set(int i){m_x = i;}
    	operator%(const MyClass& mc){return m_x % mc.m_x;}//for Myclass
    	operator%(int i){return m_x % i;}//For Ints
    protected:
    	int m_x;
    };
    
    int main( void )
    {
    
    	MyClass x,
    		    y;
    
    	x.Set(100);
    	y.Set(9);
    
    	std::cout << "x%y = " << x % y << std::endl;
    
    	std::cout << "x%13 = " << x % 13 << std::endl;
    	return 0;
    }

  3. #3
    Registered User
    Join Date
    Sep 2002
    Posts
    2

    Thanks!

    Thanks very much!

    for some reason its been like a nightmare since computer science in high school ... i could do everything else but modulus :P.

    Well thanks again!!!
    -chris

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Overloading operators
    By ugmusicbiz in forum C++ Programming
    Replies: 2
    Last Post: 02-13-2009, 01:41 PM
  2. unary operator overloading and classes
    By coletek in forum C++ Programming
    Replies: 9
    Last Post: 01-10-2009, 02:14 AM
  3. overloading operator problems
    By almich in forum C++ Programming
    Replies: 2
    Last Post: 07-26-2004, 04:10 PM
  4. overloading
    By theLukerBoy in forum C++ Programming
    Replies: 6
    Last Post: 11-04-2002, 08:49 PM
  5. using modulus & weighting factors
    By task in forum C Programming
    Replies: 4
    Last Post: 09-11-2002, 05:52 PM