C++ Tutorial/Operators statements/Operators

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Demonstrates built-in arithmetic operators

#include <iostream>
using namespace std;
int main()
{
      cout << "7 + 3 = " << 7 + 3 << endl;
      cout << "7 - 3 = " << 7 - 3 << endl;
      cout << "7 * 3 = " << 7 * 3 << endl;
      cout << "7 / 3 = " << 7 / 3 << endl;
      cout << "7.0 / 3.0 = " << 7.0 / 3.0 << endl;
      cout << "7 % 3 = " << 7 % 3 << endl;
      cout << "7 + 3 * 5 = " << 7 + 3 * 5 << endl;
      cout << "(7 + 3) * 5 = " << (7 + 3) * 5 << endl;
      return 0;
}

Demonstrating operators .* and ->*.

#include <iostream>
using std::cout;
using std::endl;
class MyClass
{
public:
   void myFunction()
   {
      cout << "In myFunction function\n";
   }
   int value;
};
void f( MyClass * );
void f2( MyClass * );
int main()
{
   MyClass myFunction;
   myFunction.value = 8;
   f( &myFunction );
   f2( &myFunction );
   return 0;
}
void f( MyClass *myFunctionPtr )
{
   void ( MyClass::*memPtr )() = &MyClass::myFunction;
   ( myFunctionPtr->*memPtr )();
}
void f2( MyClass *myFunctionPtr2 )
{
   int MyClass::*vPtr = &MyClass::value;
   cout << ( *myFunctionPtr2 ).*vPtr << endl;
}
In myFunction function
8

Precedence of C Operators

Highest   ( ) [ ] - >   
            ! ~ ++ -- - (type)  * & sizeof   
            * / %   
            + -   
            <<  >>   
            < <= > >=   
            == !=   
            &   
            ^   
            |   
            &&   
            ||   
            ?   
            = += -= *= /=   
Lowest       ,

Using the & and * operators

#include <iostream>
using std::cout;
using std::endl;
int main()
{
   int a;
   int *aPtr; 
   a = 7; 
   aPtr = &a;
   cout << "The address of a is " << &a << "\nThe value of aPtr is " << aPtr;
   cout << "\n\nThe value of a is " << a << "\nThe value of *aPtr is " << *aPtr;
   cout << "\n\nShowing that * and & are inverses of " << "each other.\n&*aPtr = " << &*aPtr
      << "\n*&aPtr = " << *&aPtr << endl;
   return 0;
}
The address of a is 0x22ff74
The value of aPtr is 0x22ff74
The value of a is 7
The value of *aPtr is 7
Showing that * and & are inverses of each other.
&*aPtr = 0x22ff74
*&aPtr = 0x22ff74

Using the unary scope resolution operator

#include <iostream>
using std::cout;
using std::endl;
int n = 7; 
int main()
{
   double n = 10.5;
   cout << "Local double value of n = " << n
      << "\nGlobal int value of n = " << ::n << endl;
   return 0;
}
Local double value of n = 10.5
Global int value of n = 7