C++ 教程目录

函数探幽

strtref.cpp

来源: 函数探幽

点击上方按钮打开代码编辑器和可视化视图

⚠️ 交互式运行提示

为了防止网页挂起,所有 cin 输入语句已被自动注释。请直接在代码编辑器中修改变量的值来进行测试。

书本配套例题

原始代码预览

// strtref.cpp -- using structure references
#include <iostream>
using namespace std;
struct sysop
{
    char name[26];
    char quote[64];
    int used;
};

const sysop & use(sysop & sysopref);  // function with a reference return type

int main()
{
// NOTE: some implementations require using the keyword static
// in the two structure declarations to enable initialization
    sysop looper =
    {
        "Rick \"Fortran\" Looper",
        "I'm a goto kind of guy.",
        0
    };

    use(looper);            // looper is type sysop
    cout << "Looper: " << looper.used << " use(s)\n";
    sysop copycat;
    copycat = use(looper);
    cout << "Looper: " << looper.used << " use(s)\n";
    cout << "Copycat: " << copycat.used << " use(s)\n";
    cout << "use(looper): " << use(looper).used << " use(s)\n";
    // cin.get();
    return 0;
}

// use() returns the reference passed to it
const sysop & use(sysop & sysopref)
{
    cout << sysopref.name << " says:\n";
    cout << sysopref.quote << endl;
    sysopref.used++;
    return sysopref; 
}
C++ Playground
运行结果 / 调试信息
等待编译...
Graph loading...
0 / 0