static int a=10;//全局静态变量
static void add();//静态函数
int main()
{
{
static int b=10;//局部静态变量
}
}
class Cperson
{
private:
static int age;
static int getAge();
}
//类外初始化
int Cperson::age = 18;
int Cperson::getAge()
{
return age;
}
int main()
{
Cperson person1;
person.age = 20;//调用并改变静态成员
//直接通过类名就可调用
cout << Cperson::age; //20
Cperson::getAge();
}
#include <iostream>
using namespace std;
class widget
{
public:
widget()
{
count++;
}
~widget()
{
count--;
}
static int num()
{
return count;
}
private:
static int count;
};
int widget::count = 0;
int main()
{
widget x, y;
cout << "The Num.is " << widget::num() << endl;
if(widget::num() > 1)
{
widget x, y, z;
cout << "The Num.is " << widget::num() << endl;
}
widget z;
cout << "The Num.is " << widget::num() << endl;
return 0;
}
class Cperson
{
private:
float height;
static int age;
static void setPerson();
}
int Cperson::age=18;
void Cperson::setPerson()
{
age=20;//正确,可调用静态成员
height=178;//错误,不可调用普通成员
}
class Cperson
{
private:
const int age;//常量数据成员
float height;
public:
Cperson(int age,float height);
};
Cperson::Cperson(int age,float height):age(age)
{
this->height=height;
}
class Cperson
{
private:
const int age;//常量数据成员
float height;
public:
int getAge()const;
void setHeight(float height);
};
int Cperson::getAge()const
{
//age++;//错误做法,不准对成员变量进行修改
return age;
}
void Cperson::setHeight(float height)
{
this->height=height;
}
int main()
{
Cperson person1;
person1.getAge();//正确
person1.setHeight(175.5);//正确
const Cperson person1;
//person1.setHeight(175.5);错误,const对象不能调用非const函数
person1.getAge();//正确
}
calss Person
{
int age;
public:
Person& setAge(int age);//一
const Person& setAge(int age)const;//二
};
int main()
{
Person p1;
const Person p2;
p1.setAge(18);//调用第一个
p2.setAge(20);//调用第二个
}