引用(五)

///看了个引用的小程, 发现我需要复习了。。。。。。

#include<iostream>
using namespace std;
#include<string>
struct free_throws
{
    std::string name;
    int made;
    int attempts;
    float percent;
};

void display(const free_throws & ft);
void set_pc(free_throws & ft);
free_throws & accumulate(free_throws & target, const free_throws & source);


int main()
{
    free_throws one = {"aaa", 13, 14};
    free_throws two = {"bbb", 10, 16};
    free_throws three = {"ccc", 7, 9};
    free_throws four = {"ddd", 5, 9};
    free_throws five = {"eee", 6, 14};
    free_throws team = {"fff", 0, 0};

    free_throws dup;

    set_pc(one);
    display(one);
    accumulate(team, one);
    display(team);

    display(accumulate(team, two));
    accumulate(accumulate(team, three), four);
    display(team);

    dup = accumulate(team, five);
    std::cout << "Displaying team:\n";
    display(team);
    std::cout << "Displaying dup after assignment:\n";
    display(dup);
    set_pc(four);

    accumulate(dup, five) = four;
    std::cout << "Displaying dup after ill-advised assignment:\n";
    display (dup);
    return 0;
}

void display(const free_throws & ft)
{
    using std::cout;
    cout << "Name: " << ft.name <<endl;
    cout << " Made: " << ft.made <<"\t";
    cout << " Attempts: " << ft.attempts << "\t";
    cout << " Precents: " << ft.percent << "\n";
}

void set_pc(free_throws & ft)
{
    if(ft.attempts != 0)
        ft.percent = 100.0f * float(ft.made)/float(ft.attempts);
    else
        ft.percent = 0;
}
free_throws & accumulate(free_throws & target, const free_throws & source)
{
    target.attempts += source.attempts;
    target.made += source.made;
    set_pc(target);
    return target;
}
/*
Name: aaa
 Made: 13        Attempts: 14    Precents: 92.8571
Name: fff
 Made: 13        Attempts: 14    Precents: 92.8571
Name: fff
 Made: 23        Attempts: 30    Precents: 76.6667
Name: fff
 Made: 35        Attempts: 48    Precents: 72.9167
Displaying team:
Name: fff
 Made: 41        Attempts: 62    Precents: 66.129
Displaying dup after assignment:
Name: fff
 Made: 41        Attempts: 62    Precents: 66.129
Displaying dup after ill-advised assignment:
Name: ddd
 Made: 5         Attempts: 9     Precents: 55.5556

Process returned 0 (0x0)   execution time : 0.689 s
Press any key to continue.

*/

///下面对以前对引用的总结做一些补充,前面我们已经讲到了左值引用,
///而C++11新增了另一种引用
///右值引用。 这种引用可指向右值。用&&声明。
double && rref = std::sqrt(36.00); /// not allowed for double &
double j = 15.0;
double && jref = 2.0*j + 18.5;/// not allowed for double &
std::cout << rref << endl;///display 6.0
std::cout << jref << endl;///display 48.5

常规(非引用)返回类型是右值,即不能通过地址访问的值。其他右值包括
字面值(如10.0)和表达式(如x+y)。
常规函数表达式返回值为右值,是因为这种返回值位于临时内存单元中。
运行到下一条语句时, 他们可能不再存在。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值