📜  C ++中的Const关键字

📅  最后修改于: 2021-05-31 16:45:19             🧑  作者: Mango

本文讨论了在C++中发现的const关键字的各种功能。每当const关键字与任何method(),变量,指针变量以及类的对象一起附加时,它将阻止该特定的object / method()/ variable修改其数据项值。

常量变量

对于常量变量的声明和初始化,有一些规则:

  • 赋值时不能将const变量保留为未初始化状态。
  • 不能在程序中的任何地方为其分配值。
  • 在声明常量变量时,需要为常量提供显式值。

const变量

下面是C++程序来演示上述概念:

C++
// C++ program to demonstrate the
// the above concept
#include 
using namespace std;
 
// Driver Code
int main()
{
 
    // const int x;  CTE error
    // x = 9;   CTE error
    const int y = 10;
    cout << y;
 
    return 0;
}


C++
// C++ program to demonstrate the
// above concept
#include 
using namespace std;
 
// Driver Code
int main()
{
    int x{ 10 };
    char y{ 'M' };
 
    const int* i = &x;
    const char* j = &y;
 
    // Value of x and y can be altered,
    // they are not constant variables
    x = 9;
    y = 'A';
 
    // Change of constant values because,
    // i and j are pointing to const-int
    // & const-char type value
    // *i = 6;
    // *j = 7;
 
    cout << *i << " " << *j;
}


C++
// C++ program to demonstrate the
// above concept
#include 
using namespace std;
 
// Driver Code
int main()
{
    // x and z non-const var
    int x = 5;
    int z = 6;
 
    // y and p non-const var
    char y = 'A';
    char p = 'C';
 
    // const pointer(i) pointing
    // to the var x's location
    int* const i = &x;
 
    // const pointer(j) pointing
    // to the var y's location
    char* const j = &y;
 
 
    // The values that is stored at the memory location can modified
    // even if we modify it through the pointer itself
    // No CTE error
    *i = 10;
    *j = 'D';
 
    // CTE because pointer variable
    // is const type so the address
    // pointed by the pointer variables
    // can't be changed
    // *i = &z;
    // *j = &p;
 
    cout << *i << " and " << *j
        << endl;
    cout << i << " and " << j;
 
    return 0;
}


C++
// C++ program to demonstrate
// the above concept
#include 
using namespace std;
 
// Driver code
int main()
{
    int x{ 9 };
 
    const int* const i = &x;
   
    // *i=10;  
    // The above statement will give CTE
    // Once Ptr(*i) value is
    // assigned, later it can't
    // be modified(Error)
 
    char y{ 'A' };
 
    const char* const j = &y;
   
    // *j='B';
    // The above statement will give CTE
    // Once Ptr(*j) value is
    // assigned, later it can't
    // be modified(Error)
 
    cout << *i << " and " << *j;
 
    return 0;
}


C++
// C++ program to demonstrate
// the above concept
#include 
using namespace std;
 
int foo(int* y)
{
    return *y;
}
 
// Driver code
int main()
{
    int z = 8;
    const int* x = &z;
    cout << foo(x);
    return 0;
}


C++
// C++ program to demonstrate the
// constant function
#include 
using namespace std;
 
// Class Test
class Test {
    int value;
 
public:
    // Constructor
    Test(int v = 0)
    {
        value = v;
    }
 
    // We get compiler error if we
    // add a line like "value = 100;"
    // in this function.
    int getValue() const
    {
        return value;
    }
     
    // a nonconst function trying to modify value
    void setValue(int val) {
        value = val;
    }
};
 
// Driver Code
int main()
{
    // Object of the class T
    Test t(20);
 
    // non-const object invoking const function, no error
    cout << t.getValue() << endl;
     
    // const object
      const Test t_const(10);
   
    // const object invoking const function, no error
    cout << t_const.getValue() << endl;
   
    // const object invoking non-const function, CTE
    // t_const.setValue(15);
     
    // non-const object invoking non-const function, no error
    t.setValue(12);
     
    cout << t.getValue() << endl;
 
    return 0;
}


C++
// C++ program to demonstrate the
// above approach
#include 
using namespace std;
 
// Function foo() with variable
// const int
void foo(const int y)
{
    // y = 6; const value
    // can't be change
    cout << y;
}
 
// Function foo() with variable int
void foo1(int y)
{
    // Non-const value can be change
    y = 5;
    cout << '\n'
         << y;
}
 
// Driver Code
int main()
{
    int x = 9;
    const int z = 10;
   
    foo(z);
    foo1(x);
 
    return 0;
}


C++
// C++ program for the above approach
#include 
using namespace std;
 
const int foo(int y)
{
    y--;
    return y;
}
 
int main()
{
    int x = 9;
    const int z = 10;
    cout << foo(x) << '\n'
         << foo(z);
 
    return 0;
}


C++
// C++ program for the above approach
#include 
using namespace std;
 
const int foo(const int y)
{
    // y = 9; it'll give CTE error as
    // y is const var its value can't
    // be change
    return y;
}
 
// Driver code
int main()
{
    int x = 9;
    const int z = 10;
    cout << foo(x) << '\n'
         << foo(z);
 
    return 0;
}


输出:
10

错误声明所面临的错误如果尝试在不分配显式值的情况下初始化const变量,则会生成编译时错误(CTE)。

带有指针变量的常量关键字

可以使用const关键字声明指针。因此,可以通过以下三种方式将const关键字与指针一起使用:

当。。。的时候 指针变量指向const值

句法:

const data_type* var_name;

下面是实现以上概念的C++程序:

C++

// C++ program to demonstrate the
// above concept
#include 
using namespace std;
 
// Driver Code
int main()
{
    int x{ 10 };
    char y{ 'M' };
 
    const int* i = &x;
    const char* j = &y;
 
    // Value of x and y can be altered,
    // they are not constant variables
    x = 9;
    y = 'A';
 
    // Change of constant values because,
    // i and j are pointing to const-int
    // & const-char type value
    // *i = 6;
    // *j = 7;
 
    cout << *i << " " << *j;
}
输出:
9 A

说明:在上面的情况下,i和j是两个指针变量,它们指向一个内存位置const int-type和char-type,但是可以像上面所做的那样更改存储在这些对应位置的值。

否则会出现以下错误:如果我们试图修改常量变量的值。

当const指针变量指向值时

句法:

data_type* const var_name;

下面是演示上述概念的示例:

C++

// C++ program to demonstrate the
// above concept
#include 
using namespace std;
 
// Driver Code
int main()
{
    // x and z non-const var
    int x = 5;
    int z = 6;
 
    // y and p non-const var
    char y = 'A';
    char p = 'C';
 
    // const pointer(i) pointing
    // to the var x's location
    int* const i = &x;
 
    // const pointer(j) pointing
    // to the var y's location
    char* const j = &y;
 
 
    // The values that is stored at the memory location can modified
    // even if we modify it through the pointer itself
    // No CTE error
    *i = 10;
    *j = 'D';
 
    // CTE because pointer variable
    // is const type so the address
    // pointed by the pointer variables
    // can't be changed
    // *i = &z;
    // *j = &p;
 
    cout << *i << " and " << *j
        << endl;
    cout << i << " and " << j;
 
    return 0;
}
输出:
9 and M
0x7ffd1ff8f830 and MC

说明:存储在相应的指针变量i和j中的值是可修改的,但是由const指针变量指出的存储x和y的相应值所指向的位置是不可修改的。

否则,将出现以下错误:指针变量是const,指向x和y的存储位置,如果我们尝试更改地址位置,则将遇到错误。

当const指针指向const变量时

句法:

const data_type* const var_name;

下面是C++程序来演示上述概念:

C++

// C++ program to demonstrate
// the above concept
#include 
using namespace std;
 
// Driver code
int main()
{
    int x{ 9 };
 
    const int* const i = &x;
   
    // *i=10;  
    // The above statement will give CTE
    // Once Ptr(*i) value is
    // assigned, later it can't
    // be modified(Error)
 
    char y{ 'A' };
 
    const char* const j = &y;
   
    // *j='B';
    // The above statement will give CTE
    // Once Ptr(*j) value is
    // assigned, later it can't
    // be modified(Error)
 
    cout << *i << " and " << *j;
 
    return 0;
}
输出:
9 and A

说明:在这里,const指针变量指向const变量。因此,既不允许更改const指针变量(* P),也不允许更改存储在该指针变量(* P)指向的位置的值

否则,将出现以下错误:此处的指针变量和指针变量指向的位置均为const,因此,如果对它们的任何一个进行了修改,都会出现以下错误:

通过常量参数的值的函数造成误差的非const参数传递常量参数值的函数的非const参数无效它给你一个编译时错误。

下面是C++程序来演示上述概念:

C++

// C++ program to demonstrate
// the above concept
#include 
using namespace std;
 
int foo(int* y)
{
    return *y;
}
 
// Driver code
int main()
{
    int z = 8;
    const int* x = &z;
    cout << foo(x);
    return 0;
}
输出:
20

输出:将出现仿佛const的值被传递给函数的任何非const参数,那么就会出现下面的编译时间错误的编译时间错误:

简而言之,以上讨论可以总结如下:

常量方法

像成员函数和成员函数参数一样,类的对象也可以声明为const 。声明为const的对象无法修改,因此只能调用const成员函数,因为这些函数确保不修改该对象。

句法:

const Class_Name Object_name;
  • 当函数声明为const时,可以在任何类型的对象,const对象以及非const对象上调用它。
  • 每当将对象声明为const时,都需要在声明时对其进行初始化。但是,只有在构造函数的帮助下,才可以在声明时进行对象初始化。

常量函数声明有两种方式:

普通的const函数声明

const void foo()
{
   //void foo() const Not valid
}                  
int main()
{
   foo(x);
}  

该类的const成员函数

class
{
   void foo() const
   {
       //.....
   }
}

以下是常量函数的示例:

C++

// C++ program to demonstrate the
// constant function
#include 
using namespace std;
 
// Class Test
class Test {
    int value;
 
public:
    // Constructor
    Test(int v = 0)
    {
        value = v;
    }
 
    // We get compiler error if we
    // add a line like "value = 100;"
    // in this function.
    int getValue() const
    {
        return value;
    }
     
    // a nonconst function trying to modify value
    void setValue(int val) {
        value = val;
    }
};
 
// Driver Code
int main()
{
    // Object of the class T
    Test t(20);
 
    // non-const object invoking const function, no error
    cout << t.getValue() << endl;
     
    // const object
      const Test t_const(10);
   
    // const object invoking const function, no error
    cout << t_const.getValue() << endl;
   
    // const object invoking non-const function, CTE
    // t_const.setValue(15);
     
    // non-const object invoking non-const function, no error
    t.setValue(12);
     
    cout << t.getValue() << endl;
 
    return 0;
}
输出:
20

如果您尝试从const对象调用non-const函数,则会出现以下错误

常数函数参数和返回类型

一个函数()的参数和 函数()的返回类型可以声明为常量。 常量值不能更改,因为任何这样的尝试都会产生编译时错误。

下面是实现上述方法的C++程序:

C++

// C++ program to demonstrate the
// above approach
#include 
using namespace std;
 
// Function foo() with variable
// const int
void foo(const int y)
{
    // y = 6; const value
    // can't be change
    cout << y;
}
 
// Function foo() with variable int
void foo1(int y)
{
    // Non-const value can be change
    y = 5;
    cout << '\n'
         << y;
}
 
// Driver Code
int main()
{
    int x = 9;
    const int z = 10;
   
    foo(z);
    foo1(x);
 
    return 0;
}
输出:
10
5

说明:将显示以下错误:

  • // y = 6; const值不能更改或修改。

对于const返回类型函数()的返回类型为const,因此它向我们返回const整数值。下面是实现上述方法的C++程序:

C++

// C++ program for the above approach
#include 
using namespace std;
 
const int foo(int y)
{
    y--;
    return y;
}
 
int main()
{
    int x = 9;
    const int z = 10;
    cout << foo(x) << '\n'
         << foo(z);
 
    return 0;
}
输出:
8
9

没有什么实质性的问题,通过const或非const变量的函数,因为这会被函数返回的值会自动保持恒定。由于该函数的参数是非常量。

对于const return type和const parameter这里,函数的return type和parameter都是const类型。下面是实现上述方法的C++程序:

C++

// C++ program for the above approach
#include 
using namespace std;
 
const int foo(const int y)
{
    // y = 9; it'll give CTE error as
    // y is const var its value can't
    // be change
    return y;
}
 
// Driver code
int main()
{
    int x = 9;
    const int z = 10;
    cout << foo(x) << '\n'
         << foo(z);
 
    return 0;
}
输出:
9
10

说明:在这里,const和非const值都可以作为const参数传递给函数,但是由于参数是const,因此我们不允许更改传递的变量的值。否则,我们将面临如下错误:

// y = 9;它会产生编译时错误,因为y是常量变量,其值无法更改。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”