zoukankan      html  css  js  c++  java
  • 面向对象程序设计-C++_课时19const_课时20不可修改的

    error C2131: 表达式的计算结果不是常数

     1 #include <iostream>
     2 using namespace std;
     3 
     4 void main()
     5 {
     6     const int class_size = 12;
     7     int finalGrade[class_size];
     8 
     9     int a = 12;
    10     int arr[a];//error C2131: 表达式的计算结果不是常数
    11 
    12     int x;
    13     std::cin >> x;
    14     const int size = x;
    15     double classAverage[size];//error C2131: 表达式的计算结果不是常数
    16 
    17     system("pause");
    18 }

    指向常量的指针

    const int * p;

    常量指针

    int x=5;

    int * const p=&x;

    指向常量的常量指针

    int x=2;

    const int * const p=&x;

    error C3892: “s1”: 不能给常量赋值

     1 #include <iostream>
     2 using namespace std;
     3 
     4 void main()
     5 {
     6     const char * s1 = "hello world";
     7     char s2[] = "hello world";
     8 
     9     std::cout << s1 << std::endl;
    10     std::cout << s2 << std::endl;
    11 
    12     s1[0] = 'a';//error C3892: “s1”: 不能给常量赋值
    13     s2[0] = 'a';
    14 
    15     std::cout << s1 << std::endl;
    16     std::cout << s2 << std::endl;
    17 
    18     printf("s1=%p
    ", &s1);
    19     printf("s2=%p
    ", &s2);
    20 
    21     system("pause");
    22 }

    const对象

    1常量成员

    2常引用作为函数参数

    3常对象

    类名 const 对象名(参数表);//必须初始化

    4常成员函数

    类型标识符 函数名(参数列表) const;

     1 #include <iostream>
     2 using namespace std;
     3 
     4 class A
     5 {
     6     const int i;
     7 public:
     8     A() :i(0)
     9     {
    10 
    11     }
    12     void f()
    13     {
    14         std::cout << "f()" << std::endl;
    15     }
    16     void f() const
    17     {
    18         std::cout << "f() const" << std::endl;
    19     }
    20 };
    21 
    22 void main()
    23 {
    24     const A a;
    25     a.f();
    26 
    27     A a1;
    28     a1.f();
    29 
    30     system("pause");
    31 }

    在常成员函数里,不能更新对象的数据成员,也不能调用该类中没有用const修饰的成员函数。如果将一个对象说明为常对象,则通过该对象只能调用它的const成员函数,不能调用其它成员函数。

  • 相关阅读:
    struts2重点——ValueStack和OGNL
    struts2基础——请求与响应、获取web资源
    struts2基础——最简单的一个例子
    servlet、filter、listener、interceptor之间的区别和联系
    服务器端组件
    自定义JSTL标签和函数库
    常见前端效果实现
    HTTP Cookie/Session
    获取动态SQL查询语句返回值(sp_executesql)
    WPF数据绑定
  • 原文地址:https://www.cnblogs.com/denggelin/p/5635356.html
Copyright © 2011-2022 走看看