- 重载运算符:operator
//修改之前的point add()
point operator+(point &p1,point &p2){
point n;
n.x = p1.x + p2.x;
n.y = p1.y + p2.y;
return n;
}
//调用
point a;
point b;
point c = a+b;
- 友元函数
将一个函数声明为一个类的朋友,则其可以直接访问类的私有数据.
class point{
private:
int x;
int y;
public :
setX();
setY();
frined point add(point &p1,point &p2);
};
point add(point &p1,point &p2){
point n;
n.x = p1.x + p2.x;
n.y = p1.y + p2.y;
return n;
}
- 类中静态成员归该类所有,并不属于实例化对象.
用static修饰,修饰完后无法引用到非static成员.
class persoon{
private:
static int cnt;
public:
static int getCnt();
};
7.1. 构造方法传参数赋值成员变量.
class student{
public:
person father;
person mother;
student(){
cout<<"student"<<endl;
}
student(const char* fname,const char* mname,int fage,int mage):father(fname,fage),mother(mname,mage)
{
cout<<"student"<<endl;
}
};
- 构造,析构函数
a. 可以有多个构造函数,但是只能有一个析构函数.在对象被释放前调用.
b. cpp中直接声明就会调用到构造函数,可以不用手动调用delete也会除法析构.
c. 按运行的顺序调用构造函数,静态对象只调用一次构造函数,全局对象会最先执行.
d. 如果一个类的成员中声明了另一个类,则声明该类是会先调用到成员类的构造函数再调用到自己的构造函数.最先声明的析构最先调用.
class student{
public :
person father;
person mother;
student(){}
};
int main()
{
person per;
person per("rain",18);
person *p = new person;//可以不带括号
person *p1 = new person();
person *p2 = new person[2];//获取两个实例对象
//通过指针new出来的需要手动delete掉.
delete p;
delete p1;
delete p2;
return 0;
}
class person
{
public:
person(){}
person(char*name,int age){}
~person()
{
if (this->name) {
cout << "name = "<<name<<endl;
delete this->name;
}
}
}
- 默认参数
test(int a,int b = 3,char* name = NULL);
- 引用,对变量取一个别名.
a.定义时需要赋值初始化.
b.只能引用变量.
//b是a的引用,b会指向a的地址
int a = 100;
int &b = a;
int add(int a)
{
return a = a+1;
}
//指针
int add(int *a)
{
return *a = *a + 1;
}
//引用
int add_ref(int &b)
{
return b = b+1;
}
int main()
{
int a = 99;
add(a); //a=99
add(&a);//a=100
add_ref(a);//a=101
return 0;
}
- 命名空间
当引入多个类中有相同函数时,link报错:multiple definition.
由此引入命名空间:
namespace A{
class person{
public:
void print();
}
}
namespace B{
class dog{
public:
void print();
}
}
//调用
A::print();
B::print();
A::person per;
per.print();
//或者使用using
using A::persion;
using B::dog;
//或者直接使用命名空间
using namespace A;
using namespace B;
- 头文件.h , 实现类.cpp和Makefile
#include <stdio.h>
class Persion{
private:
char* name;
int age;
public:
void setName(char* name);
void setAge(int age);
};
#include "person.h"
void person::setName(char *name)
{
this->name=name;
}
void person::setAge(int age)
{
this->age=age;
}
#include "person.h"
int main()
{
person p;
}
person: main.o person.o
g++ -o $@ $^
# $@ 表示生成对象, $^ 表示所有依赖, $< 表示第一个依赖
main.o:main.cpp
g++ -c -o $@ $<
clean:
rm -rf *.o person
- struct 的升级 class,相比struct , class里可以直接实现方法而不用传递指针.
struct person{
char *name;
char *work;
int age;
void (*printinfo)(*person);
}
class Person{
public:
char *name;
char *work;
int age;
void printInfo(void){
printf("xx");
}
}
- 将class里的方法提取出来, 用双冒号重写.
class Person{
public:
char *name;
char *work;
int age;
void printInfo(void);
}
void Person::printInfo(void){
printf("xx")
}