You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

类指针数组浅拷贝:如何修正Picture_Pair的拷贝构造函数?

Fixing the Shallow Copy Constructor for Your Picture_Pair Class

Let's break down what's wrong with your current code and fix it step by step.

1. Name Collision Problem

Your copy constructor parameter is named pp, which clashes with your class's private member array pp. When you write pp = pp.pp, you're actually trying to access the parameter's non-existent pp member instead of the source object's pointer array. We need to rename the parameter to avoid this conflict—other is a standard, readable choice.

2. Array Assignment Limitation

You can't directly assign one array to another using the = operator in C++. For a shallow copy of your pointer array, you need to copy each element individually.

Here's the corrected version of your class with a proper shallow copy constructor:

#ifndef PICTURE_PAIR_H
#define PICTURE_PAIR_H

class Picture; // Forward declaration

class Picture_Pair {
private:
    Picture* pp[2] {nullptr, nullptr}; // Pointers to the two Pictures

public:
    // Shallow copy constructor
    Picture_Pair(const Picture_Pair& other) {
        // Copy each pointer individually (shallow copy)
        pp[0] = other.pp[0];
        pp[1] = other.pp[1];
    }

    // Add a default constructor (required since we defined a user-defined copy constructor)
    Picture_Pair() = default;

    // Don't forget to declare/destructors if you manage Picture object lifetimes!
};

#endif // PICTURE_PAIR_H

What This Does

  • The shallow copy constructor takes a const Picture_Pair& other (the source object we're copying from).
  • We copy each pointer in other.pp to our own pp array. This means both the original Picture_Pair and the new copy will point to the same Picture objects—this is exactly the behavior of a shallow copy.

Critical Note

Since this is a shallow copy, watch out for double deletion if your Picture_Pair class is responsible for deleting the Picture objects. If both the original and copied Picture_Pair try to delete the same pointers in their destructors, you'll get undefined behavior. If you ever need a deep copy (where each Picture_Pair owns its own Picture instances), you'd have to allocate new Picture objects and copy their data instead of just copying pointers.

内容的提问来源于stack exchange,提问作者Micka1895

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:22:50