c++函数传递参数以及返回值

学习函数传递参数以及返回值

C++ 中函数传递参数与变量初始化一样。

比如变量初始化:

​ int a =22;

​ char ch='w';

​ char &ch_1=ch;

​ int *p=&a;

​ ........

那么函数形参的初始化也一样:

​ void(int a); : void(22);

​ void(char ch); : void('w');

​ void(char &ch_1); : void(ch);

​ void(int *p); : void(&a);

​ ...............

函数返回值:

函数声明什么类型,函数就应该返回什么类型值。

下面这个程序就是练习列表初始化返回值(c++11标准)。

C++11新标准规定,函数可以返回花括号包围的值的列表。

Example 1:

#include<iostream>
#include<string>
#include<vector>
#include<unistd.h>  //linux 下包含getpass(“ ”)无回显函数。
using namespace std;
vector<char> get_password();
vector<string> nag(const string &name);
int main()
{   vector<string> name;
    char *password;
    cout<<"请输入帐号:"<<endl;
    string username;
    cin>>username;
    name=nag(username);
    cout<<name[0]<<endl;
    if(name[0]=="Your username is true.Please enter your password.")
    {  password=getpass(" ");

      cout<<"Your password is :"<<password<<endl;;
}    else
      ;
    return 0;
}
vector<string> nag(const string &name)
{
    if(name=="yearinyearout")
    {
      return{"Your username is true.Please enter your password."};
    }
    else
    {
      return {"sorry!Not have the account."};
    }
}

Run:


xiandonghua@No:~/c++/c++bin$ ./function_1 
请输入帐号:
yearinyearout
Your username is true.Please enter your password.
 
Your password is :123456
xiandonghua@No:~/c++/c++bin$ 

这个程序的主要意图是练习函数的形参初始化和列表初始化返回值,所以程序本身有点不恰当。


一步一步慢慢学,不怕学的比别人慢,就怕什么也没学懂。

----至自己

猜你喜欢

转载自blog.csdn.net/arctic_fox_cn/article/details/80331031