class and struct
目录
前文
c++ 中的class 和struct
struct 默认为 public
class 默认为private
问题
左值引用,右值引用区别?
什么时候需要定值浅拷贝和深拷贝的函数。
传值和传值的区别
对象与引用
引用的传递
返回引用就意味着是data[ind]的別名。
using namespace std;
class Vector{
public:
Vector(int n =100) : n(n),data(new int[n]){}
int &at(int ind){return data[ind];}
private :
int n ;
int *data;
};
int main(){
Vector arr;
for(int i=0; i< 1; i++){
arr.at(i) = i;
}
return 0;
}
对象 copy
实际上两种copy是逻辑上的
class Vector{
public:
Vector(int n =100) : n(n),data(new int[n]){}
int &at(int ind){
cout << "ind" << ind << endl;
return data[ind];
}
int &operator[](int ind) {return data[ind];}
void output (int m = -1){
if(m == -1) m = n;
cout <<"Arr" << this << endl;
for(int i = 0; i < m; i++){
cout << data[i] << " ";
}
cout << endl;
return ;
}
private :
int n ;
int *data;
};
shallow copy
int main(){
Vector arr;
for(int i=0; i< 10; i++) arr[i]=i;
arr.output(10);
Vector arr2(arr);
arr2.output(10);
arr2[3]=1000;
arr.output(10);
arr2.output(10);
return 0;
}
Arr0x7ffcddc92630 arr
0 1 2 3 4 5 6 7 8 9
Arr0x7ffcddc92620 arr 2
0 1 2 3 4 5 6 7 8 9
Arr0x7ffcddc92630
0 1 2 1000 4 5 6 7 8 9
Arr0x7ffcddc92620
0 1 2 1000 4 5 6 7 8 9
arr {n=100 data=0x000002196c4ad400 {0} } Vector
arr2 {n=100 data=0x000002196c4ad400 {0} } Vector
vs 的debug 模式下 data
本代码将arr 拷贝给了arr2 ,本身属于两个不同的对象。
既然属于不同的对象,arr2的变动不应对arr1发生改变,但是事与愿违 ,因为受拷贝行为的影响,依次性的拷贝,由于是指针域,拷贝了同一个存储区的值。所以 arr2 发生更改,arr1 也会发生更改。
?如果copy 的对象是指针类型时,这个方式就无法适用了.
depthcopy
指针类型并非是赋值关系,存arr2 应该是一个额外的存储区。
memcpy(data,a.data,sizeof(T) *n);
当前方法在一定的简单类型的场景下可以进行深拷贝,如果类型中存在了指针类型则也会出现两个指针指向同一个地址的的情况。
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstring>
using namespace std;
#define BEGINS(x) namespace x {//begin of namespace
#define ENDS(x)} //end of namespace x
BEGINS(xxx)
class A {
public :
int x , y;
};
ostream &operator<<(ostream &out ,const A &a){
out << "(" << a.x << " , " << a.y << ")";
return out;
}
template<typename T>
class Vector{
public:
Vector(int n =100) : n(n),data(new T[n]){}
Vector (const Vector &a): n(a.n){
// 实现深拷贝
data = new T[n];
/*
for(int i = 0; i < n; i++){
data[i]=a.data[i];
} */
//实现以上的效果
//1 : memcpy 可能是复制类型是复杂类型的对象
memcpy(data,a.data,sizeof(T) *n);
return ;
}
T &at(int ind){
cout << "ind" << ind << endl;
return data[ind];
}
T &operator[](int ind) {return data[ind];}
void output (int m = -1){
if(m == -1) m = n;
cout << "Arr size " << sizeof(data) << " " << this << endl;
for(int i = 0; i < m; i++){
cout << data[i] << " ";
}
cout << endl;
return ;
}
private :
int n ;
T *data;
};
ENDS(xxx)
简单类型
BEGINS(test1)
using namespace xxx;
int main(){
Vector<int> arr;
for(int i=0; i< 10; i++) arr[i]=i;
arr.output(10);
Vector<int> arr2(arr);
arr2.output(10);
arr2[3]=1000;
arr.output(10);
arr2.output(10);
return 0;
}
ENDS(test1)
Arr size 8 0