引用之一
程序员文章站
2022-05-13 21:18:59
...
#include <iostream>
//引用
//1)作为形参
void f1(int a)
{
a = 0;
}
void f2(int& a)
{
a = 0;
}
class A
{
int a[1024];
};
void f3(A a)
{
}
void f4(A& a)
{
}
//2)作为返回值
int global = 10;
int g1()
{
return global;//返回的是临时量
}
int& g2()
{
return global;//返回值是个变量
}
void main()
{
int b = 1;
f1(b);
std::cout<<b<<std::endl;//1
f2(b);
std::cout<<b<<std::endl;//0
A c;
f3(c);//拷贝1024字节
f4(c);//拷贝4字节
int r = g1();
//g1() = 4;//左操作数必须为左值
r = g2();
g2() = 4;//等同于 global = 4;
std::cout<< global <<std::endl;
}
附
#include <iostream>
class A
{
int* p;
public:
A()
{
p = new int[10];
}
A(const A& that)
{
p = new int[10];
for (int i = 0;i < 10; ++i)
p[i] = that.p[i];
}
~A()
{
delete [] p;
}
//赋值运算符重载
//1)返回值是类的引用
A& operator = (const A& that)
{
if (this != &that)
{
delete [] p;
p = new int[10];
for (int i = 0;i < 10; ++i)
p[i] = that.p[i];
}
return *this;
}
};
class SXB
{
int* p;
int size;
int len;
public:
SXB();
SXB(const SXB& that);//拷贝构造
//同类赋值
};
void main()
{
A a;
A b(a);
A c;
c = a;//等同于 c.operator=(a);
c = c;
}
上一篇: LINUX基础命令
下一篇: c++学习 打卡第三天《引用》 补发