const数据成员存活在对象中,类可以创建不同 的对象,每个对象的const数据成员值可以不同,通过构造函数初始化
static数据成员作用域是整个类,类创建的不同的对象共享同一个static数据成员,不能通过构造函数初始化,因为他属于类,不属于对象。在类定义文件初始化。
static const和const static一样,创建整个类都恒定的常量
#ifndef _HEADER_H_
#define _HEADER_H_
class Base
{
public:
Base(int bb);
void print();
private:
static int aa; //静态成员变量,不能在类内部定义,不能使用构造函数初始化。
const int bb = 20; //常量成员变量,只能通过构造函数初始化,VS2013居然编译通过。
static const int cc = 10; //可以在类内部定义,与const static int cc = 10相同
};
#endif
#include "Header.h"
#include <stdio.h>
#include <iostream>
Base::Base(int bb)
:bb(bb)
{
aa++;
}
void Base::print()
{
std::cout << "aa = " << aa << std::endl;
std::cout << "bb = " << bb << std::endl;
std::cout << "cc = " << cc << std::endl;
}
int Base::aa = 100;
//const int Base::cc = 222; //或者在这里初始化
#include <stdio.h>
#include <iostream>
#include "Header.h"
int main()
{
Base test(10);
test.print();
Base test1(13);
test1.print();
}