关于含有指针成员的类的对象之间赋值指针的问题。
在C++ 中,当定义了一个类,类的成员中有指针的时候,需要注意:如果将类的对象A赋值给B的时候,两个对象的指针是指向同一个地址的,其余的变量都是相等的。在图像处理中,比如定义了一个图像类,类成员中有具体的图像数据,如果将两个对象直接相等,会使两个对象的数据指针指向同一个地址。如果要使两个对象的指向不同的地址可以为类定义一个函数,用于两个对象之间的直接赋值运算。下面以例子说明。
声明了一个类:
class CImgData
{
public:
int *pimgdata = new int [10];
int width;
int height;
};
主函数:
int main()
{
CImgData A;
A.width = 2;
A.height = 3;
for (int i = 0; i < 10; i++)
{
A.pimgdata[i] = i * 7 + 5;
}
cout << "A 的地址是: " << endl;
cout << A.pimgdata << endl;
CImgData B;
//ACImgDataToBCImgData(A, B);
B = A;
cout << "B 的地址是: " << endl;
cout << B.pimgdata << endl;
for (int m = 0; m < 10; m++)
cout << B.pimgdata[m] << endl;
cout << "B.width= " << B.width << endl;
cout << "B.height=" << B.height << endl;
cout << "completed" << endl;
}运行结果:
可以看出:A和B的数据指针的地址相同,相关的变量被复制。
改进:为类添加对象赋值函数
void ACImgDataToBCImgData(CImgData A, CImgData B)
{
B.height = A.height;
B.width = A.width;
for (int i = 0; i < 10; i++)
{
B.pimgdata[i] = A.pimgdata[i];
}
}
主函数:
int main()
{
CImgData A;
A.width = 2;
A.height = 3;
for (int i = 0; i < 10; i++)
{
A.pimgdata[i] = i * 7 + 5;
}
cout << "A 的地址是: " << endl;
cout << A.pimgdata << endl;
CImgData B;
ACImgDataToBCImgData(A, B);
cout << "B 的地址是: " << endl;
cout << B.pimgdata << endl;
for (int m = 0; m < 10; m++)
cout << B.pimgdata[m] << endl;
cout << "B.width= " << B.width << endl;
cout << "B.height=" << B.height << endl;
cout << "completed" << endl;
return 0;
}运行结果如下:
结果显示:两个对象的指针地址不一样,因此连个对象的没有联系,只是单纯将相关的数据复制传递。但是,注意到这个时候width和height两个成员没有传递,是因为,数据变量作为函数的形参传递的时候,使用的拷贝的临时变量。
改进:使用引用传递。
将函数改为如下,其余的部分不变:
void ACImgDataToBCImgData(CImgData &A, CImgData &B)
{
B.height = A.height;
B.width = A.width;
for (int i = 0; i < 10; i++)
{
B.pimgdata[i] = A.pimgdata[i];
}
}结果如下:
结果显示:两个对象的地址不同,同时相关变量的数据值成功传递。
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇: C++中指针的强制转换。
