C++ Primer第七章 函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fuck51cto/article/details/80921211

C++ Primer第七章 函数



1.  函数的定义

   函数由函数名以及一组操作数类型唯一地表示。函数的操作数,也即形参,在一对圆括号中声明,形参与形参之间以逗号分隔。函数执行的运算在一个称为函数体的块语句中定义。每一个函数都有一个相关联的返回类型。

    形参和实参
形参是一个函数的局部变量
实参则是一个表达式,在调用函数时,所传递的实参个数必须与函数的形参个数完全相同。



     

2. 指针形参

    函数可以修改指针所指向的值。

const 形参
在函数中,不可以改变实参的局部副本。由于实参仍然是以副本的形式传递,因此传递给 fcn 的既可以是 const 对象也可以是非 const 对象。
  void fcn(const int i) { /* fcn can read but not write to i */ }

  void fcn(int i) { /* ... */ }            // error: redefines fcn(int)

引用形参
       函数可以修改实参的值,const 引用相反,不能修改。



数组形参
     数组形参的定义
            void printValues(int*) { /* ... */ }
    void printValues(int[]) { /* ... */ }
            void printValues(int[10]) { /* ... */ }

3. 函数中的对象

局部对象
局部对象在函数调用结束时,对象就会销毁。

静态局部对象

在该函数被多次调用的过程中,静态局部对象会持续存在并保持它的值。

	size_t count_calls() {
		    static size_t ctr = 0;
		    return ++ctr;
		}

		int _tmain(int argc, _TCHAR* argv[]) {
		    for (size_t i = 0; i!=10; ++i) {
		        cout<<count_calls()<<endl;
		    }
		    return 0;
		}
		这个程序会依次输出 1 到 10(包含 10)的整数。

4. 内联函数

将函数指定为内联是建议编译器在调用点直接把函数代码展开。内联函数避免了调用函数的代价

          将函数指定为 inline 函数,(通常)就是将它在程序中每个调用点上“内联地”展开。假设我们将 shorterString 定义为内联函数,则调用:

          cout << shorterString(s1, s2) << endl;

	   const string &shorterString(const string &s1, const string &s2)
	     {
	         return s1.size() < s2.size() ? s1 : s2;
	     }


5. 类的成员函数

this 指针的引入
this 是指向当前对象的一个指针


6. const 成员函数

只能读取而不能修改类成员



7. 函数重载

在 C++ 中,函数可以重载。只要函数中形参的个数或类型不同


8. 指向函数的指针

函数指针是指指向函数而非指向对象的指针。像其他指针一样,函数指针也指向某个特定的类型。函数类型由其返回类型以及形参表确定,而与函数名无关:

扫描二维码关注公众号,回复: 5763010 查看本文章

  bool (*pf)(const string &, const string &);
这个语句将 pf 声明为指向函数的指针,它所指向的函数带有两个 const string& 类型的形参和 bool 类型的返回值。



用 typedef 简化函数指针的定义
   typedef bool (*cmpFcn)(const string &, const string &);
    该定义表示 cmpFcn 是一种指向函数的指针类型的名字。该指针类型为“指向返回 bool 类型并带有两个 const string 引用形参的函数的指针”。
        在要使用这种函数指针类型时,只需直接使用 cmpFcn 即可,不必每次都把整个类型声明全部写出来。
   bool lengthCompare(const string &, const string &)

   调用:

cmpFcn pf = lengthCompare;
lengthCompare("hi", "bye"); // direct call
pf("hi", "bye");            // equivalent call: pf1 implicitly dereferenced
(*pf)("hi", "bye");         // equivalent call: pf1 explicitly dereferenced


函数指针作为形参传递

		typedef void (*PrintStr)(const string &);

		void printing(const string &str) {
		    printf("%s\n",str.c_str());
		}


		void test_print(PrintStr print,const string &str) {
		    print(str);
		}

		int _tmain(int argc, _TCHAR* argv[]) {
		    test_print(printing,"Hello world");
		    return 0;
		}






























猜你喜欢

转载自blog.csdn.net/fuck51cto/article/details/80921211