Tutorial - C / C++ - Operator


Coding Friends Tutorial Index - > C / C++

Author Ian - Tutorial Posts = 62
An operator syntax is part of the standard C/C++ syntax that allows you to use the +/-/* etc aspects of the objects that are assoicated with them, for example, for two values of an integer you can add these two values together with value1 + value2, the adding part is calculated within the operator and the value is returned.

To code a operator you just need to use the <return type> operator <insert type of operator>(<passed parameter(s)>) function. Within the code below there are 3 types of operators for the operate test class, to add another integer to the internal value, to increament the internal value and also to logically add the internal value with another integer value.

The code
---


#include <iostream>

using namespace std;

class optest
{
public :
       int i ;
       optest() { i = 0; }
       optest(int i2) { i = i2;}
       
       virtual int out() { return i;}

       int operator +(int addi)
       {
              return i + addi;
       }

       int operator++(int)
       {
              return ++i;
       }

       int operator &(int addi)
       {
              return i&addi;
       }
};

class optest2 : public optest       // inhert the base class for showing how to use operators within base class and inherited classes
{
public:
       int out() { return i + 10;}
       optest2() : optest() {;}
       optest2(int i) : optest(i) {;}
};

int main(int argc, char* argv[])
{
       // setup and demo the results of the operators
       optest op(3);
       optest2 op2(2);
       cout << op.out() << endl;
       cout << op + 3 << endl;
       cout << op.out() << endl;
       cout << op++ << endl;
       cout << op.out() << endl;
       cout << op2.out() << endl;
       return 0;
}


---

I have included Microsoft Visual Studio 2005 downloadable edition (here) and also Linux code for this tutorial as a download.
Creation of cool tutorials :)
User Name Password
Copyright@CodingFriends, 2005-2006. All Rights Reserved.
Home | Forums | Tutorials | Users
RSS Feeds - Global Global CodingFriends RSS Feed - Tutorials Tutorials CodingFriends RSS Feed - Forums Forums CodingFriends RSS Feed - News News CodingFriends RSS Feed
Users
Login|Password problem| Register here

Tutorials
Tutorials Home| C/C++| C#/Mono| Java| Javascript| PHP| Ruby| SQL| (X)HTML/CSS| VB| Linux| Windows

Forum
Forum Home

Projects
3D Game

Site
Home| About me| Links| FAQ

Search