一.类的申明
class 类名
{
private:
私有的数据和成员函数;
public:
公用的数据和成员函数;
protected:
保护的数据和成员函数
};
二.类的成员函数
构造函数(类的初始化,创建类时自动调用;初始化表,this指针)
默认构造函数 A();
#include <stdio.h>class A{
public:A(){printf("A()\n");}A(int data){printf("A(int data)\n");}~A(){printf("A~~~~~~~~~~~~~\n");}
};int main()
{//called when new object is created!A *p = new A(1000);A x;A m(100);A y = 10;A z = y;
}
拷贝构造函数 A(const A &x);
#include <stdio.h>
#include <string.h>class A{
public:A(){printf("A()\n");p = new char[10];strcpy(p, "hello");printf("p: %s\n", p);printf("p: %s\n", this->p);}A(const A &x){printf("A(const A &x)\n");p = new char[10];strcpy(p, x.p); }~A(){printf("~A()\n");delete [] p;}private:char *p;
};int main()
{A x;A y = x;// y = x;
}
赋值构造函数 operator=?;
析构函数(类的解构,销毁类时自动调用)
~A();
普通成员函数
三.常成员、常对象
常数据成员(构造函数初始化表赋值)
class A{
public: A():x(100) { }
const int x;
}
常成员函数
void func() const;
常对象
const A a;
#include <stdio.h>class A{
public:A(int a = 50, int data = 1000):b(data){
// b = data;this->a = a;printf("AAAAAAAAA\n");}~A(){printf("~~~~~~~~~\n");}void show(void) const{printf("b = %d\n", b);printf("a = %d\n", a);// a++;// b++;}
private:int a;const int b;
};int main()
{A x(10);x.show();A y(100);y.show();A z;z.show();
}
四.静态成员
静态成员的申明
static int x;
static const int x = 10;
静态数据成员初始化
类外: static int A::x = 10;
静态成员函数
static void func(); //能访问静态成员
调用方法 A::func();
#include <stdio.h>class A{
public:static void func(void){printf("xxxxxxxxx\n");}static int data;
};int A::data = 10;int main()
{A a;a.func();A::func();A x;x.data = 100;printf("x.data = %d\n", x.data);A::data = 1000;printf("x.data = %d\n", x.data);
}
五.友元
友元类
friend class B;
友元函数
friend void func();
友元成员函数
friend void B::func();
#include <stdio.h>class A;class B{
public:void printfA(A &x);
};class A{
public:A(){x = 100;}// friend class B;friend void B::printfA(A &x);
private:int x;
};void B::printfA(A &x)
{printf("%d\n", x.x);
}int main()
{A a;
// printf("%d\n", a.x);B b;b.printfA(a);
}