1. 程式人生 > 其它 >c++如何call其他程式的函式_C/C++的函式與程式結構

c++如何call其他程式的函式_C/C++的函式與程式結構

技術標籤:c++如何call其他程式的函式

一、函式基礎

返回值型別 函式名(引數列表)

{

宣告和語句;

return X;

}

示例:

#include

using namespace std;

int f1()

{

return 1;

}

float f2()

{

return 1.0f;

}

char f3()

{

return 'B';

}

int main() {

cout << f1() << endl;

cout << f2() << endl;

cout << f3() << endl;

return 0;

}

輸出結果:

1

1

B

示例2:

#include

using namespace std;

void increase(int x)

{

for(int i = 1;i<=5;i++)

++x;

}

int main() {

int a = 0;

increase(a);

cout << a << endl;

return 0;

}

輸出結果:

0

上述示例中,再呼叫increase方法時,將a的值賦值給了x,並進行相關計算,a的值並沒有因此發生改變。

如果想要直接對a進行操作,只需要定義為&x,將x定義為引用型。(在C++環境中)

示例如下:

#include

using namespace std;

void increase(int &x)

{

for(int i = 1;i<=5;i++)

++x;

}

int main() {

int a = 0;

increase(a);

cout << a << endl;

return 0;

}

輸出結果:

5

&可以靠近變數,也可以靠近型別。

int &x

int& x

定義為引用型變數,變數只能傳入變數,不可以傳入常量。

二、作用域

示例1:

#include

using namespace std;

void f()

{

int a = 10;

}

int main() {

int a = 0;

f();

cout << a << endl;

return 0;

}

輸出結果:

0

示例2:

#include

using namespace std;

void f(int a)

{

a = 10;

}

int main() {

int a = 0;

f(a);

cout << a << endl;

return 0;

}

輸出結果:

0

示例3:

#include

using namespace std;

int a = 10;

void f()

{

++a;

cout << a << endl;

}

int main() {

cout << a << endl;

f();

return 0;

}

輸出結果:

10

11

示例4:

#include

using namespace std;

int a = 10;

void f()

{

int a = 5;

cout << a << endl;

}

int main() {

cout << a << endl;

f();

return 0;

}

輸出結果:

10

5

示例5:

#include

using namespace std;

int main() {

int a = 10;

{

int a = 5;

cout << "inside:" << a << endl;

}

cout << "outside:" << a << endl;

return 0;

}

輸出結果:

inside:5

outside:10

當內部作用域中的變數名與外部作用域的變數名相同時,內部作用域會遮蔽掉外部作用域的變數,外部作用域無法直接呼叫內部作用域的變數。

三、靜態變數

示例1:

#include

using namespace std;

void f(){

int a = 0;

++a;

cout << a << endl;

}

int main() {

for (int i = 0; i < 5; ++i) {

f();

}

return 0;

}

輸出結果:

1

1

1

1

1

在上述示例中,for迴圈,迴圈5次,迴圈列印了5個1,沒有出現累加操作。每次呼叫f(),都會重新定義一個a,f()呼叫結束後,a被回收。

如果要使得每次呼叫f()時操作的時同一個a,需要給a增加一個static的修飾。

示例2:

#include

using namespace std;

void f(){

static int a = 0;

++a;

cout << a << endl;

}

int main() {

for (int i = 0; i < 5; ++i) {

f();

}

return 0;

}

輸出結果:

1

2

3

4

5

個人部落格:http://www.coderlearning.cn/

dc21b0677826023e5bab5b8850c24eca.png