C++ 函数参数

2018-03-24 17:09 更新

学习C++ - C++函数参数

函数参数和值传递

C++通常通过值传递参数。

例如,

double volume = cube(side);

这边是一个变量,在运行中,值为5。

cube()的函数头是这样的:

double cube(double x)

调用此函数时,将创建一个新的类型double变量x,并将其初始化为5。

多个参数

一个函数可以有多个参数。

在函数调用中,你只需用逗号分隔参数:


#include <iostream>
using namespace std;
void n_chars(char, int);
int main()
{
    int times;
    char ch;

    cout << "Enter a character: ";
    cin >> ch;
    while (ch != "q")        // q to quit
    {
        cout << "Enter an integer: ";
        cin >> times;
        n_chars(ch, times); // function with two arguments
        cout << "\nEnter another character or press the q-key to quit: ";
           cin >> ch;
    }
    cout << "The value of times is " << times << ".\n";

    return 0;
}

void n_chars(char c, int n) // displays c n times
{
    while (n-- > 0)         // continue until n reaches 0
        cout << c;
}

上面的代码生成以下结果。

函数和数组

以下代码说明如何使用指针,就像它是一个数组名称一样。

该程序将数组初始化为某些值,并使用sum_arr()函数来计算和。


#include <iostream>
using namespace std;

const int SIZE = 8;
int sum_arr(int arr[], int n);        // prototype
int main()
{
    int cookies[SIZE] = {1,2,4,8,16,32,64,128};
    int sum = sum_arr(cookies, SIZE);
    cout << "Total cookies eaten: " << sum <<  "\n";
    return 0;
}

// return the sum of an integer array
int sum_arr(int arr[], int n){
    int total = 0;
    for (int i = 0; i < n; i++)
        total = total + arr[i];
    return total; 
}

上面的代码生成以下结果。

数组名称与数组指针

以下代码显示了Cookie和arr具有相同的值。

它显示了指针如何使sum_arr函数更加通用。

该程序使用std:: qualifier而不是using指令来提供对cout和endl的访问。


#include <iostream>
const int ArSize = 8;
int sum_arr(int arr[], int n);

int main()
{
    int cookies[ArSize] = {1,2,4,8,16,32,64,128};
    std::cout << cookies << " = array address, ";
    std::cout << sizeof cookies << " = sizeof cookies\n";
    int sum = sum_arr(cookies, ArSize);
    std::cout << "Total cookies eaten: " << sum <<  std::endl;
    sum = sum_arr(cookies, 3);        // a lie
    std::cout << "First three eaters ate " << sum << " cookies.\n";
    sum = sum_arr(cookies + 4, 4);    // another lie
    std::cout << "Last four eaters ate " << sum << " cookies.\n";
  return 0;
}
int sum_arr(int arr[], int n){
    int total = 0;
    std::cout << arr << " = arr, ";
    std::cout << sizeof arr << " = sizeof arr\n";
    for (int i = 0; i < n; i++)
        total = total + arr[i];
    return total; 
}

上面的代码生成以下结果。

使用数组范围的函数

以下代码使用两个指针来指定范围。


#include <iostream>
using namespace std;
const int SIZE = 8;
int sum_arr(const int * begin, const int * end);
int main()
{
    int cookies[SIZE] = {1,2,4,8,16,32,64,128};
    int sum = sum_arr(cookies, cookies + SIZE);
    cout << "Total cookies eaten: " << sum <<  endl;
    sum = sum_arr(cookies, cookies + 3);        // first 3 elements
    cout << "First three eaters ate " << sum << " cookies.\n";
    sum = sum_arr(cookies + 4, cookies + 8);    // last 4 elements
    cout << "Last four eaters ate " << sum << " cookies.\n";
    return 0;
}
int sum_arr(const int * begin, const int * end){
    const int * pt;
    int total = 0;

    for (pt = begin; pt != end; pt++)
        total = total + *pt;
    return total; 
}

上面的代码生成以下结果。

函数和C风格字符串

以下代码计算给定字符在字符串中出现的次数。

因为程序不需要处理负值,它使用unsigned int作为计数类型。


#include <iostream>
using namespace std;
unsigned int c_in_str(const char * str, char ch);
int main()
{
    char mmm[15] = "minimum";    // string in an array
    char *wail = "ululate";    // wail points to string

    unsigned int ms = c_in_str(mmm, "m");
    unsigned int us = c_in_str(wail, "u");
    cout << ms << " m characters in " << mmm << endl;
    cout << us << " u characters in " << wail << endl;
    return 0;
}
// counts the number of ch characters in the string str
unsigned int c_in_str(const char * str, char ch)
{
    unsigned int count = 0;
    while (*str)        // quit when *str is "\0"
    {
        if (*str == ch)
            count++;
        str++;        // move pointer to next char
    }
    return count; 
}

上面的代码生成以下结果。

返回C风格字符串的函数

以下代码定义了一个返回指针的名为buildstr()的函数。

此函数有两个参数:一个字符和一个数字。

使用new,该函数创建一个长度等于数字的字符串,然后将每个元素初始化为字符。

然后它返回一个指向新字符串的指针。


#include <iostream>
using namespace std;
char * buildstr(char c, int n);     
int main()
{
    int times;
    char ch;

    cout << "Enter a character: ";
    cin >> ch;
    cout << "Enter an integer: ";
    cin >> times;
    char *ps = buildstr(ch, times);
    cout << ps << endl;
    delete [] ps;                   // free memory
    ps = buildstr("+", 20);         // reuse pointer
    cout << ps << "-DONE-" << ps << endl;
    delete [] ps;                   // free memory
    return 0;
}
// builds string of characters
char * buildstr(char c, int n){
    char * pstr = new char[n + 1];
    pstr[n] = "\0";         // terminate string
    while (n-- > 0)
        pstr[n] = c;        // fill rest of string
    return pstr; 
}

上面的代码生成以下结果。

传递和返回结构


#include <iostream>
using namespace std;

struct my_time
{
    int hours;
    int mins;
};
const int MINUTES = 60;

my_time sum(my_time t1, my_time t2);
void show_time(my_time t);

int main()
{
    my_time day1 = {5, 45};    // 5 hrs, 45 min
    my_time day2 = {4, 55};    // 4 hrs, 55 min

    my_time trip = sum(day1, day2);
    show_time(trip);
    return 0;
}

my_time sum(my_time t1, my_time t2)
{
    my_time total;
    total.mins = (t1.mins + t2.mins) % MINUTES;
    total.hours = t1.hours + t2.hours + (t1.mins + t2.mins) / MINUTES;
    return total;
}

void show_time(my_time t)
{
    cout << t.hours << " hours, " << t.mins << " minutes\n";
}

上面的代码生成以下结果。

函数和字符串类对象

以下代码提供了一个简短的示例,它声明一个字符串对象数组,并将该数组传递给显示内容的函数。


#include <iostream>
#include <string>
using namespace std;
const int SIZE = 5;
void display(const string sa[], int n);

int main()
{
    string list[SIZE];     // an array holding 5 string object
    cout << "Enter your " << SIZE << " favorite astronomical sights:\n";
    for (int i = 0; i < SIZE; i++){
        cout << i + 1 << ": ";
        getline(cin,list[i]);
    }

    cout << "Your list:\n";
    display(list, SIZE);
  return 0; 
}
void display(const string sa[], int n){
    for (int i = 0; i < n; i++)
        cout << i + 1 << ": " << sa[i] << endl;
}

上面的代码生成以下结果。

函数和数组对象


#include <iostream>
#include <array>
#include <string>
const int Seasons = 4;
const std::array<std::string, Seasons> Snames = 
   {"Baseball", "Football", "Basketball", "Hockey"};

void fill(std::array<double, Seasons> * pa);
void show(std::array<double, Seasons> da);

int main(){
    std::array<double, 4> expenses;
    fill(&expenses);
    show(expenses);
    return 0;
}

void fill(std::array<double, Seasons> * pa){
    for (int i = 0; i < Seasons; i++){
        std::cout << "Enter " << Snames[i] << " expenses: ";
        std::cin >> (*pa)[i];
    }
}

void show(std::array<double, Seasons> da){
    double total = 0.0;
    for (int i = 0; i < Seasons; i++){
        std::cout << Snames[i] << ": $" << da[i] << "\n";
        total += da[i];
    }
    std::cout << "Total: $" << total << "\n";
}

上面的代码生成以下结果。

C++内联函数

内联函数可以加速程序。

以下代码说明了使用inline square()函数的内联技术。


#include <iostream>
using namespace std;
inline double square(double x) { return x * x; }
int main(){
    double a, b;
    double c = 13.0;

    a = square(5.0);
    b = square(4.5 + 7.5);   // can pass expressions
    cout << "a = " << a << ", b = " << b << "\n";
    cout << "c = " << c;
    cout << ", c squared = " << square(c++) << "\n";
    cout << "Now c = " << c << "\n";
    // cin.get();
    return 0;  
}

上面的代码生成以下结果。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号