C++ Tutorial/Operators statements/Operators
Содержание
Demonstrates built-in arithmetic operators
<source lang="cpp">#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;
}</source>
Demonstrating operators .* and ->*.
<source lang="cpp">#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;
}</source>
In myFunction function 8
Precedence of C Operators
<source lang="cpp">Highest ( ) [ ] - >
! ~ ++ -- - (type) * & sizeof * / % + - << >> < <= > >= == != & ^ | && || ? = += -= *= /=
Lowest ,</source>
Using the & and * operators
<source lang="cpp">#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;
}</source>
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
<source lang="cpp">#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;
}</source>
Local double value of n = 10.5 Global int value of n = 7