zoukankan      html  css  js  c++  java
  • static-const 类成员变量

     【本文链接】

    http://www.cnblogs.com/hellogiser/p/static-const.html

    【分析】

    const数据成员必须在构造函数初始化列表中初始化;

    static数据成员必须在全局范围进行初始化,不能有static限定符,例如int CLASS::size=100;

    对于static const成员和const static成员而言,只有int类型可以在内部初始化,任何类型都可以在类外初始化,但是不可以在构造函数列表初始化,需要添加const关键字。例如const int CLASS:size=100;

    【代码】

     C++ Code 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
     
    /*
        version: 1.0
        author: hellogiser
        blog: http://www.cnblogs.com/hellogiser
        date: 2014/9/20
    */


    #include "stdafx.h"
    #include "iostream"
    using namespace std;


    class MyClass
    {
    public:
        MyClass(
    int size): size1(size)
        {

        }
        ~MyClass()
        {

        }
        
    const int size1; // Member Initializer List
        static int size2; // outside class

        
    static const int size3 = 150//only int can be initialized inside class
        static const int size4;
    };

    int MyClass::size2 = 100// static
    const int MyClass::size4 = 200// static const


    void test_class_const_static_variable()
    {
        MyClass obj(
    50);
        cout << obj.size1 << endl;
        cout << obj.size2 << endl;
        cout << obj.size3 << endl;
        cout << obj.size4 << endl;
    }

    int main()
    {
        test_class_const_static_variable();
        
    return 0;
    }
    /*
    50
    100
    150
    200
    */

    【代码2】

     C++ Code 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    class Test
    {
    public:
        Test(): a(
    0) {}
        
    enum {size1 = 100, size2 = 200};
    private:
        
    const int a;//只能在构造函数初始化列表中初始化
        static int b;//在类的实现文件中定义并初始化
        const static int c;//与 static const int c;相同。
    };

    int Test::b = 0//static成员变量不能在构造函数初始化列表中初始化,因为它不属于某个对象。
    cosnt int Test::c = 0//注意:给静态成员变量赋值时,不需要加static修饰符。但要加cosnt

    【参考】

    http://blog.csdn.net/gukesdo/article/details/7435805

    个人学习笔记,欢迎拍砖!---by hellogiser

    Author: hellogiser
    Warning: 本文版权归作者和博客园共有,欢迎转载,但请保留此段声明,且在文章页面明显位置给出原文连接。Thanks!
    Me: 如果觉得本文对你有帮助的话,那么【推荐】给大家吧,希望今后能够为大家带来更好的技术文章!敬请【关注】
  • 相关阅读:
    POJ3159 Candies —— 差分约束 spfa
    POJ1511 Invitation Cards —— 最短路spfa
    POJ1860 Currency Exchange —— spfa求正环
    POJ3259 Wormholes —— spfa求负环
    POJ3660 Cow Contest —— Floyd 传递闭包
    POJ3268 Silver Cow Party —— 最短路
    POJ1797 Heavy Transportation —— 最短路变形
    POJ2253 Frogger —— 最短路变形
    POJ1759 Garland —— 二分
    POJ3685 Matrix —— 二分
  • 原文地址:https://www.cnblogs.com/hellogiser/p/static-const.html
Copyright © 2011-2022 走看看