📜  C ++中静态函数和常量函数之间的区别

📅  最后修改于: 2021-05-31 20:04:05             🧑  作者: Mango

静态函数这是一个成员函数,仅用于访问静态数据成员。它不能访问非静态数据成员,甚至不能调用非静态成员函数。即使不存在该类的对象,也可以调用它。它还用于在类的不同对象之间维护类成员函数的单个副本。

程序1:

C++
// C++ program to illustrate the use
// of static function
#include "bits/stdc++.h"
using namespace std;
  
class A {
public:
    static void f()
    {
        cout << "GeeksforGeeks!";
    }
};
  
// Driver Code
int main()
{
    A::f();
}


C++
// C++ program to illustrate the use
// of const keyword
  
#include 
using namespace std;
  
// Driver Code
int main()
{
    const double a = 1;
  
    // Using the below line of code
    // gives error
    // a = 2.21;
  
    cout << a << endl;
  
    return 0;
}


输出:
GeeksforGeeks!

常量函数此函数通常在程序中声明为常量。它还保证它不允许修改对象或调用任何非const成员函数。它指定该函数是只读函数,并且不会修改为其调用该对象的对象。

程式2:

C++

// C++ program to illustrate the use
// of const keyword
  
#include 
using namespace std;
  
// Driver Code
int main()
{
    const double a = 1;
  
    // Using the below line of code
    // gives error
    // a = 2.21;
  
    cout << a << endl;
  
    return 0;
}
输出:
1

静态函数和常量函数之间的表格差异:

Static Function

Constant Function

It is declared using the static keyword.   It is declared using the const keyword.  
It does not allow variable or data members or functions to be modified again. Instead, it is allocated for a lifetime of the program.   It allows specifying whether a variable is modifiable or not.
It helps to call functions that using class without using objects.   It helps us to avoid modifying objects.  
This function can only be called by static data members and static member functions.   This function can be called using any type of object. 
It is useful to declare global data which should be updated while the program lives in memory, used to restrict access to functions, reuse the same function name in other files, etc.   It is useful with pointers or references passed to function, used to avoid accidental changes to object, can be called by any type of object, etc. 
It is a member function that generally allows accessing function using class without using an instance of the class.   It is a member function that is generally declared as constant in the program. 
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”