[C++] Fucntions

Statements

A break statements terminate the nearest wile, do while, for or switch statement. A break affect only the nearest enclosing loop or switch.

As any block, variables declared inside a try block are inaccessible outsite the block - in particular, they are not accessible to the catch clauses.

Exception.

A try block maigh call a function that contains a try which calls another funciton with its own try and so on. The search for a hander reverses the call chain. If no appropriate catch is found, execution is transfered to a library function name terminate. The terminate will garantee to stop further execution of th problem.

If there are no try blocks, they can be no handlers. If a program no try blocks and an exception occurs, then terminate is called and program is exited.

Programs that properly "clean up" during execution handling are saied to be "exception safe".

Functions

Parameters and Arguments

Arguments are the initilizers for a function‘s parameters.

Local Objects

In C++, names have scopes, and objects have lifetimes

  • The scope of a name is the part of the program‘s text in which that name is visible.
  • The lifetime of an object is the time during the program‘s execution that the object exists.

Parameters and variables defined inside a function body are refered to as local variables. They are "local" to that function and hide declaration of the same name made on outer scope.

Obejcts defined outside any functions exist through the program‘s execution. Such object are created then the program starts and not destroyed until the program ends

The lifetime of varibles depends on how it is defined.

Automatic object. Objects that exist only when a block is execution are known as automatic objects.

local static object. Each local static object is initilized before the first time execution pass through the object‘s definition. Local static objects are not destroyed when a funciton ends; they are destroyed when the program terminated.

size_t count_calls(){
    static size_t ctr = 0;    // value will persist across calss
    ctr++;
    return ctr;
}
int main(){
    for (size_t i = 0; i != 10; i++){
        cout << count_calls() << endl;
    }
}

This program will print the number from 1 through 10 inclusive.

Function declartions are also known as the function prototype.

Recall that variables are declared in haeder files and defined in source file. Function should be declared in header files and defined in source file.

The header that declares a funciton should be included in that source file tha defines that function.

Argument Passing

Parameter initialization works the same way as variable initialization.

If the parameter is a reference then the parameter is bound to its argument. Otherwise, the argument‘s value is copied.

When aprameter is a reference, we say that its correspondency argument is "passed by reference", or that function is "called by referenced". As with any other reference, a reference paramter is an alisa for the object to which it is bound.

When the argument value is copied. the parametr and argument are independent object. We say such arguments are "passed by value", or the function is "called by value".

When we initiliaze a non-reference type variable or parameter, the value of the initializer is copied.

Pointers behave like any other non-reference type. When we copy a pointer, the value of the pointer is copied. After the copy, the two pointers are distinct, but pointing to the same object.

void reset(int *ip){
    *ip = 0;    // change the value of the object to which ip points
    ip = 0;    // change the local pointer; the argument is unchanged.
}

Usage:

int i = 42;
reset(&i);    // change i, but not the address of i

Programmers accustomed to programming in C often use pointer paramters to access objects outside a function. In C++, programmers generally use reference parameters instead.

Recall that operations on a reference are actully operations on the object to which the reference refers

void reset(int &i){    // i is just another name for the object passed to reset
    i = 0;          // change the value of the objet to which i refers
}

When we call this version of reset, pass an object directly, no need to pass its address.

int j = 42;
reset(j);        // passed by reference, the value on j is changed

Reference parameter that are not changed inside a function should be references to const.

Never return a reference or pointer to a local object.

When a function completes, its storage is free. After a function terminates, references to local object refer to memory that is no long valid.

// disaster: this function returns a reference to a local object
const string &mapip(){
    string ret;
    if(!ret.empty()){
        return ret;    // WRONG: return a reference to a local object
    }else{
        return "Empty";    // WRONG: "Empty" is a local object
    }
}

References returns are lvalues

Calls to function that return references are lvalu. Other return types is rvalue.

char &get_val(string &str, string::size_type ix){
    return str[it];
}
int main(){
    string s("a value");
    get_value(s, 0) = ‘A‘; // change s[0] to A
    return 0;
}

Overload Functions

Functions that have the same name but different parameter lists and that appear in the same scope are overload.

Default Arguments

sz wd = 80;
char def = ‘ ‘;
char ht();

string screen(sz = ht(), sz = wd, char = def);

void f2(){
    sz wd = 100;    // hide the definition of wd, but not change the default
    def = ‘*‘;    // change the default
    window = screen();    // call screen(ht(), 80, ‘*‘)
}

Reference:

C++ Primer, Fifth Edition, chapter 6 Functions

时间: 2024-12-24 13:22:53

[C++] Fucntions的相关文章

黄聪:wordpress工作原理

WP初始化的过程:当你输入<yourlink>/wordpress对wordpress进行初始化时,wordpress默认会找根目录下的index.php页面,看一下index.php页面. <?phpdefine('WP_USE_THEMES', true);/** Loads the WordPress Environment and Template */require('./wp-blog-header.php'); ---把/wp-blog-header.php包含进来?>

仿钢琴的声音

效果图: 当点击按钮的时候,会播放相应的钢琴的声音. 此代码需要引入库AudioToolbox.framework. 此为工程目录: RootViewController.h #import <UIKit/UIKit.h> //加入头文件 #import <AudioToolbox/AudioToolbox.h> @interface RootViewController : UIViewController { NSString *soundFile; } @end RootVi

Java Programming Tutorial Java Native Interface (JNI)

1.  Introduction At times, it is necessary to use native codes (C/C++) to overcome the memory management and performance constraints in Java. Java supports native codes via the Java Native Interface (JNI). JNI is difficult, as it involves two languag

C++11 之 &quot; = delete &quot;

1  缺省函数 设计一个类,没有成员函数 (member function),只有成员数据 (member data) class DataOnly { private: std::string strName; // member data int iData; }; 1.1  特殊成员函数 C++98 编译器会为其隐式的产生四个函数:缺省构造函数,析构函数:拷贝构造函数,拷贝赋值算子   而 C++11 编译器,除了产生这四个函数外,还会多产生两个函数:移动构造函数,移动赋值算子 class

[ Javascript ] 内存泄露以及循环引用解析

内存泄露 在javascript中,我们非常少去关注内存的管理. 我们创建变量,使用变量,浏览器关注这些底层的细节都显得非常正常. 可是当应用程序变得越来越复杂而且ajax化之后,或者用户在一个页面停留过久,我们可能须要去注意一些问题.如一个浏览器花费了1G以上的内存,而且在不断的添加. 这些问题经常都是由于内存泄露引起. Javascript 内存泄露 这个javascript内存管理的核心概念就是具不具有可达性的概念. 1 一个明显的对象集合将会被觉得是可达的:这些对象是被知道的像roots

faster-rcnn原理及相应概念解释

R-CNN --> FAST-RCNN --> FASTER-RCNN R-CNN: (1)输入测试图像: (2)利用selective search 算法在图像中从上到下提取2000个左右的Region Proposal: (3)将每个Region Proposal缩放(warp)成227*227的大小并输入到CNN,将CNN的fc7层的输出作为特征: (4)将每个Region Proposal提取的CNN特征输入到SVM进行分类: (5)对于SVM分好类的Region Proposal做边

R-CNN,SPP-NET, Fast-R-CNN,Faster-R-CNN, YOLO, SSD系列深度学习检测方法梳理

1. R-CNN:Rich feature hierarchies for accurate object detection and semantic segmentation 技术路线:selective search + CNN + SVMs Step1:候选框提取(selective search) 训练:给定一张图片,利用seletive search方法从中提取出2000个候选框.由于候选框大小不一,考虑到后续CNN要求输入的图片大小统一,将2000个候选框全部resize到227*

js 内存泄漏

在javascript中,我们很少去关注内存的管理.我们创建变量,使用变量,浏览器关注这些底层的细节都显得很正常. 但是当应用程序变得越来越复杂并且ajax化之后,或者用户在一个页面停留过久,我们可能需要去注意一些问题,如一个浏览器花费了1G以上的内存,并且在不断的增加.这些问题常常都是因为内存泄露引起. Javascript 内存泄露 这个javascript内存管理的核心概念就是具不具有可达性的概念. 1 一个明显的对象集合将会被认为是可达的:这些对象是被知道的像roots一样. 包括那些所

Objects and Data Structures

Date Abstraction Hiding implementation is not just a matter of putting a layer of fucntions between the variables.Hiding implementation is about abstractions!A class does not simply push its varivables out through getters and setters.Rather it expose