您的位置:首页 > 编程语言 > C语言/C++

C++ 学习记录 20180301

2018-03-01 16:26 239 查看
值传递:调用函数时,如果参数是个变量而不是具体的值,e.g.(void function(int n))参数传给了形式参数,不论形式参数的值如何变化,变量的值都不受影响。
引用传递:形参会变成原变量一个别名,形参变化时,变量的值也会变化。就是所谓引用传递
以引用方式调用函数:
    在调用increment函数的时候,x的值1被传递给了形式参数n,n在函数中自增了1,但是无论函数做了什么,x值都会不变。
#include "stdafx.h"
#include <iostream>
using namespace std;

void increment(int n)
{
n++;
cout << "\tn insidenthe function is " << n << endl;

}

int main()
{
int x = 1;
cout << "Before the call, x is" << x << endl;
increment(x);
cout << "after the call, x is " << x << endl;

return 0;
}


result:
    Before the call, x is1
        n insidenthe function is 2

after the call, x is 1

可以定义引用变量(reference variable)
通过引用变量来访问和修改存储在变量中的原数据。

like: void increment(int & n)
在变量类型后面加上 ‘&’
实例:#include "stdafx.h"
#include <iostream>
using namespace std;

void swap(int n1, int n2)
{
cout << "\tInside the swap the function" << endl;
cout << "\tBefore swapping n1 is " << n1 << " n2 is " << n2 << endl;

int temp = n1;
n1 = n2;
n2 = temp;
cout << "\t After swapping n1 is " << n1 << " n2 is " << n2 << endl;
}

int main()
{

int num1 = 1;
int num2 = 2;
cout << "\t Before swapping num1 is " << num1 << " num2 is " << num2 << endl;

swap(num1, num2);

cout << "\t After swapping num1 is " << num1 << " num2 is " << num2 << endl;
return 0;
}

实例:
十六进制转十进制#include "stdafx.h"
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

//function protype
//converts a hex num as a string to decimal;
int hex2Dec(const string & hex);

//converts a hex character to a decimal value;
int hexCharToDecimal(char ch);

int main()
{
cout << "Enter a hex number: ";
string hex;
cin >> hex;

cout << "The decimal value for hex number " << hex << " is " << hex2Dec(hex) << endl;

}

int hex2Dex(const string& hex)
{
int decimalValue = 0;
for (unsigned i = 0; i < hex.size(); i++)
{
decimalValue = decimalValue * 16 + hexCharToDecimal(hex[i]);
}
return decimalValue;
}

int hexCharToDecimal( char ch)
{
ch = toupper(ch);
if (ch >= 'A' && ch <= 'F')
{
return 10 + ch - 'A';

}
else
{
return ch - '0'; //两个字符相间就是他们的ASCII码相减
}
}遇到了一个bug:
严重性 代码 说明 项目 文件 行 禁止显示状态

错误 LNK2019 无法解析的外部符号 "int __cdecl hex2Dec(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (?hex2Dec@@YAHABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z),该符号在函数 _main 中被引用 201802272 C:\Users\Administrator\source\repos\201802272\201802272\201802272.obj 1

//
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: