静态成员
类内声明,类外初始化,所有对象访问同一个变量,可通过类名访问,也可通过对象访问
#include <iostream>
using namespace std;
class dev{
public:
static int cay;
};
int dev::cay = 100;
int main(){
dev a;
cout << "对象访问: " << a.cay << endl;
cout << "类名访问" << dev::cay << endl;
dev b;
b.cay = 1000;
cout << "对象访问: " << a.cay << endl;
}
静态成员函数只能访问静态成员变量,不能访问非静态变量
#include <iostream>
using namespace std;
class dev{
public:
static int cay;
static void test(){
cay = 10086;
cout << "test" << endl;
}
};
int dev::cay = 100;
int main(){
dev a;
a.test();
dev:: test();
}
类指针
#include <iostream>
using namespace std;
class dev{
public:
static int cay;
static void test(){
cay = 10086;
cout << "test" << endl;
}
dev* returndev(){
this->cay += 1;
return this;
}
};
int dev::cay = 100;
int main(){
dev a;
dev* b = a.returndev();
cout << b->cay << endl;
}
返回一个指针
返回当前对象本身
#include <iostream>
using namespace std;
class dev{
public:
static int cay;
static void test(){
cay = 10086;
cout << "test" << endl;
}
dev& returndev(){
this->cay += 1;
return *this;
}
};
int dev::cay = 100;
int main(){
dev a;
dev b = a.returndev();
cout << b.cay << endl;
}
返回一个副本
#include <iostream>
using namespace std;
class dev{
public:
static int cay;
static void test(){
cay = 10086;
cout << "test" << endl;
}
dev returndev(){
this->cay += 1;
return *this;
}
};
int dev::cay = 100;
int main(){
dev a;
dev b = a.returndev();
cout << b.cay << endl;
}