- 引用和指针在底层汇编阶段没有任何区别,都是地址传递。
- 不同:指针可能出现地址乱指的问题,而引用则不会,改变引用的值实际上是改变变量地址上的值,而不是变量的地址。
- 引用是C++中特有类型。
- 引用类型只能赋值一次,不能重新赋值。
- 引用只是变量的一个别名。
- 引用可以理解成是编译器维护的一个指针,但并不占用空间。
- 使用引用可以像指针那样去访问、修改对象的内容,但更安全。
void Printf(Base & a,Base *ap)
{
int temp = 10;
&a = &temp;//错误,引用不能重新赋值
a = 10;//正确,改变这个地址上变量的值。
ap = &temp;//正确,指针可以重新赋值,只是意义已经不同。
}
友元函数:
- 就是给这个函数访问私有成员的权限。
- 运算符重载的某些场合需要使用友元。
- 两个类要共享数据的时候。
友元函数和类的成员函数的区别:
- 成员函数有this指针,而友元函数没有this指针。
- 友元函数是不能被继承的,就像父亲的朋友未必是儿子的朋友。
#include<stdio.h>
class Student
{
private:
int x;
int y;
public:
Student(int x,int y)
{
this->x = x;
this->y = y;
}
friend void Printf1(Student* p);
friend void Printf2(const Student& p);
};
//但是现在都不能访问 想要访问私有成员,必须在类声明中声明这个函数是我这个类的朋友
void Printf1(Student* p)
{
printf("%d %d \n",p->x,p->y);
}
void Printf2(const Student& p) //加const是为了避免意外修改变量的值,但是现在仍然不能访问私有成员
{
printf("%d %d \n",p.x,p.y);
}
int main(int argc,char *argv[])
{
Student s(1,2);
Printf1(&s);
Printf2(s);
return 0;
}
运算符重载
- 就是函数替换。
- . :: ?: sizeof # 不能重载外,其余的都是可以重载的。
- 经常需要重载的运算符,就是 > < == 。
#include<stdio.h>
class Number
{
private:
int lowValue;
int highValue;
public:
Number(int lowValue,int highValue)
{
this->lowValue = lowValue;
this->highValue = highValue;
}
void Print();
//void Plus();//plus已经实现了int ++的功能,但是每次都要调用这个函数,怎么做到和普通++功能意义,而不需要自己再写这个函数呢.
Number operator++();//int++时的返回值是int,所有结构体/类的返回值必须是对应的类型。
Number operator+(const Number& p);
friend bool operator>(const Number& p1,const Number& p2);
friend bool operator<(const Number& p1,const Number& p2);
friend bool operator==(const Number& p1,const Number& p2);
};
void Number::Print()
{
printf("low = %d , high = %d\n",lowValue,highValue);
}
/*
void Number::Plus()
{
lowValue++;
highValue++;
}
*/
Number Number::operator++()
{
lowValue++;
highValue++;
return *this;
}
Number Number::operator+(const Number& p)
{
this->lowValue += p.lowValue;
this->highValue += p.highValue;
return *this;
}
bool operator>(const Number& p1,const Number& p2)
{
if((p1.lowValue > p2.lowValue) && (p1.highValue > p2.highValue))
return true;
else
return false;
}
bool operator<(const Number& p1,const Number& p2)
{
if((p1.lowValue < p2.lowValue) && (p1.highValue < p2.highValue))
return true;
else
return false;
}
bool operator==(const Number& p1,const Number& p2)
{
if((p1.lowValue == p2.lowValue) && (p1.highValue == p2.highValue))
return true;
else
return false;
}
int main(int argc,char *argv[])
{
Number n(1,2);
n.Print();
// n.Plus();//实现了++的功能,给它起个别名可以吗?
// n.Print();
n++;
n.Print();
Number n1(2,3);
n = n+n1;
n.Print();
if(n>n1)
printf("> true\n");
else
printf("> false\n");
if(n<n1)
printf("< false\n");
else
printf("< true\n");
if(n == n1)
printf("==\n");
else
printf("!=\n");
return 0;
}