static -常见的错误
正确的demo1
#include <iostream>
using namespace std;
class Man
{
public:
Man()
{
count++;
}
void play() const
{
cout<<"I am playing ..."<<endl;
}
static int getCount()
{
return count;
}
private:
static int count; /* 表示总的人数 */
};
int Man::count = 0;
int main(void)
{
Man man1;
Man man2;
cout<<Man::getCount()<<endl;
system("pause");
return 0;
}
运行结果:’
错误的代码 demo2
#include <iostream>
using namespace std;
class Man
{
public:
Man()
{
count++;
}
void play() const
{
cout<<"I am playing ..."<<endl;
}
static int getCount()
{
/* 类的static方法内, 不能调用这个类的非static方法(实例方法) */
play();
/* 类的static方法内, 不能访问非static数据成员(实例数据成员) */
cout<<age<<endl;
return count;
}
private:
static int count; /* 表示总的人数 */
int age; /* 年龄 */
};
int Man::count = 0;
int main(void)
{
Man man1;
Man man2;
cout<<Man::getCount()<<endl;
system("pause");
return 0;
}
总结:
类的静态方法(static 方法) 内, 不能访问实例方法(非 static 方法)和实例数据成员!
结语:
继续加油, 量变的积累才能引起质变
时间: 2020-06-21-14-34