1.静态成员变量,函数
class Person {
public:
static int age; };
int main(void) {
Person p;
p.age;
Person::age; }
1. 使用创建对象的方式访问, 2. 直接使用类访问, 3.静态成员函数 不能访问普通变量, 4.普通函数可以访问静态
2.单例模式
1.将类的构造函数和拷贝函数以及成员变量都设置为私有, 2.然后外部通过共有的静态方法来获取 Printer*的指针
3.静态成员变量最好在类的外部初始化 虽然是singlePrinter私有的但是加上Printer::依然是在类内
class Printer {
private:
static Printer* singlePrinter;
private:
Printer() {};
Printer(const Printer& p) {};
public:
static Printer* getInstance() {
return singlePrinter;
}
};
Printer* Printer::singlePrinter = new Printer;
3.this 是一个指针 谁调用就指向谁, *this代表对象本身 非静态成员才有
4.常函数,对象
必须是类中的函数,在后面加上 const ,表示不允许修改 this指针 指向的值 相当于 const Person * const this
class Printer {
void test() const
{ }}
1.const Person p 修饰的对象 不能再 p.age =100; 修改 2.常对象只能调用 成员常函数
5.友元函数
本来 test是类的私有方法, 所以test2不能访问, 但是在类中声明 友元函数 就可以访问了
class Printer {
friend void test();
private:
void test()
{} };
void test2()
{
Printer p;
p.test();
}
6.各种重载
7.函数模板
1. 这样 函数 就可以传入两个类型一样的任意类型了 2.如果普通的与模板函数重载, 先调用普通的 3.继承时告诉T的类型
template<class T>
void mySwap(T &a,T &b)
{ }
2.具体 模板
template<> bool test<Person>(Person &a, Person &b){}
3.类模板 ,分文件编写时,需要导入 .cpp而不是 .h 所以在写模板时, 把.cpp和.h写在一个文件 命名为 .hpp
template<class NameType ,class AgeType>
class Person
{
Person(NameType n,AgeType a) {};
};
Person<string, int> p("wyc", 15);
8.静态, 动态类型转换,常量转换
1.对于 父类 与 子类也 也可以使用这种转换
int main(void) {
char a = 'a';
double b =static_cast<double>(a);
cout << b << endl; } 97
2.动态 dynamic_cast
不能转换基本数据类型, 只能转换父类子类这种, 父转子不可以 , 子转父 可以 发生多态可以
3.常量转换
去掉const 或增加const 都可以 , 只能对指针或者应用类型的 数据进行转换
const int* m = NULL;
int* n = const_cast<int*>(m);