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

C++如何将一个类的私有成员添加到另一个类的数组中

问题解决方案

错误原因

  • 你定义的pieces数组是基类collection的实例数组,基类本身没有length、width成员,访问不存在的类成员自然会触发编译报错。
  • 类职责混淆:wallHangingType作为collection的公有派生类,逻辑上是壁挂类藏品这个具体藏品类型,不应该同时承担存储多个藏品的容器功能,你把「藏品类型」和「藏品容器」的逻辑耦合在了同一个类里。

修改方案

提供两种适配不同需求的修改方式:

方案1:拆分职责(推荐,可扩展性强)

拆分藏品类型和藏品容器,符合面向对象设计规范:

  1. 调整wallHangingType定义,仅保留壁挂类藏品本身的属性和方法:
// wallHangingType.h
#ifndef WALLHANGINGTYPE_H
#define WALLHANGINGTYPE_H
#include "collection.h"

class wallHangingType:public collection
{
public:
    wallHangingType(int id = 0, std::string name = "NA", std::string artTitle = "NA", int artLength = 0, int artWidth = 0)
    : collection(id, name, artTitle), length(artLength), width(artWidth) {}
    
    void setLength(int artLength) { length = artLength; }
    int getLength() const { return length; }
    void setWidth(int artWidth) { width = artWidth; }
    int getWidth() const { return width; }
    void printArt() const;

private:
    int length;
    int width;
};
#endif
  1. 新增独立的藏品容器类存储所有藏品,如果你需要同时存储多种类型的藏品,可以使用基类指针数组实现多态:
// collectionManager.h
#ifndef COLLECTIONMANAGER_H
#define COLLECTIONMANAGER_H
#include "collection.h"
#include "wallHangingType.h"

class CollectionManager {
public:
    CollectionManager(): index(0) {}
    void addWallHanging(int id, std::string name, std::string artTitle, int artLength, int artWidth) {
        pieces[index] = new wallHangingType(id, name, artTitle, artLength, artWidth);
        index++;
    }
    // 其他操作方法
private:
    collection* pieces[100];
    int index;
};
#endif

后续需要访问length、width时,对基类指针做dynamic_cast转换为wallHangingType*类型即可访问对应成员。

方案2:最小改动适配现有结构

如果不想调整现有类结构,仅需对wallHangingType的存储逻辑做小改即可:

  1. 修改wallHangingType.h的私有成员,新增单独的长度、宽度存储数组:
#ifndef WALLHANGINGTYPE_H
#define WALLHANGINGTYPE_H
#include "collection.h"

class wallHangingType:public collection
{
public:
    wallHangingType();
    void addPiece(int id, std::string name, std::string artTitle,int artLength, int artWidth);
    void removePiece();
    void printArt();

private:
    collection pieces[100];
    int lengthArr[100]; // 对应存储每个藏品的长度
    int widthArr[100]; // 对应存储每个藏品的宽度
    int index;
};
#endif
  1. 修改wallHangingType.cpp的addPiece实现:
void wallHangingType::addPiece(int id, std::string name, std::string artTitle,int artLength, int artWidth)
{
   pieces[index].setId(id);
   pieces[index].setArtist(name);
   pieces[index].setTitle(artTitle);
   lengthArr[index] = artLength;
   widthArr[index] = artWidth;
   index++; // 补充索引自增逻辑,避免每次覆盖同一条数据
}

访问藏品时通过相同索引即可从lengthArr、widthArr中取出对应尺寸属性。

额外注意事项

  • 原来的代码中addPiece方法没有对index做自增操作,多次调用会一直覆盖数组第0位的数据,需要补充该逻辑。
  • 如果使用多态方案,记得在类析构中释放堆内存,避免内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:24:03