C++/Function/Function Return

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

Returning a Value from a Function

#include <iostream>
using namespace std;
int addNumbers(int, int);  
int main ()
{
   int firstNum, secondNum, sum = 0;
   cout << "Enter first number: ";
   cin >> firstNum;
   cout << "Enter second number: ";
   cin >> secondNum;
   sum = addNumbers (firstNum, secondNum);
   cout << firstNum << " + " << secondNum << " = " << sum;
   return 0;
}
int addNumbers (int x, int y)
{
   return x + y;
}


Returning objects.

 
#include <iostream> 
using namespace std; 
 
class MyClass { 
  int val; 
public: 
  MyClass(int i) { 
    val = i; 
    cout << "Inside constructor\n"; 
  } 
 
  ~MyClass() { 
     cout << "Destructing\n"; 
  } 
 
  int getval() { 
     return val; 
  } 
  
  MyClass mkBigger() { 
    MyClass o(val * 2); 
 
    return o;              // Return an object. 
  } 
}; 
 
void display(MyClass ob) 
{ 
  cout << ob.getval() << "\n"; 
} 
 
int main() 
{ 
  cout << "Before constructing a.\n"; 
  MyClass a(10); 
  cout << "After constructing a.\n"; 
 
  cout << "Before call to display().\n"; 
  display(a); 
  cout << "After display() returns.\n"; 
 
  cout << "Before call to mkBigger().\n"; 
  a = a.mkBigger(); 
  cout << "After mkBigger() returns.\n"; 
 
  cout << "Before second call to display().\n"; 
  display(a); 
  cout << "After display() returns.\n"; 
 
  return 0; 
}


Return Value Of Functions

#include <iostream>
#include <iomanip>
using namespace std;
double area(double, double);
int main()
{
    double  x = 3.5, y = 1.2,  res;
    res = area( x, y+1);
    cout << fixed << setprecision(2);
    cout << " The area of a rectangle "
         << " with width  " << setw(5)  << x
         << " and length  " << setw(5) << y+1
         << " is          " << setw(5) << res
         << endl;
    return 0;
}
double area( double width, double len) {
    return (width * len); 
}