加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 将结构传递给函数

发布时间:2020-12-16 05:42:59 所属栏目:百科 来源:网络整理
导读:我正在练习不同的方法来为结构变量赋值.但当 我试过这个我得到一些垃圾的价值.这是代码. #includeiostreamusing namespace std ;struct Distance{ int feet ; int inches;};void get_val(Distance ); void disp(Distance);int main(){ Distance l,m ; //Obje
我正在练习不同的方法来为结构变量赋值.但当
我试过这个我得到一些垃圾的价值.这是代码.
#include<iostream>
using namespace std ;

struct Distance{
    int feet ;
    int inches;
};

void get_val(Distance );               
void disp(Distance);

int main(){

    Distance l,m ;                   //Objects 
    get_val(l);
    get_val(m);
    disp(l);
    disp(m);
    return 0  ;
}

void get_val(Distance length){
    cout<<"nEnter Length "
        <<"nFeet  : ";
    cin>>length.feet;
    cout<<"nInches : ";
    cin>>length.inches;
}
void disp(Distance length){
    cout<<"nLength : n"
        <<"Feet : "<<length.feet
        <<"nInches : "<<length.inches ;
}

为什么我得到垃圾值作为输出?

解决方法

通过参考.
void get_val(Distance&);


void get_val(Distance &length){}

您在另一个函数中更改在main函数中创建的结构的值,因此您必须通过引用或使用指针来传递它们.

编辑:

感谢本杰明·林德利

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读