【问题标题】:Types myObj and myObj* are not compatiblemyObj 和 myObj* 类型不兼容
【发布时间】:2016-08-21 22:51:11
【问题描述】:
class boundaryPt{
public:
friend class KCurvature;
int x;
int y;

boundaryPt(int x, int y){
    this->x = x;
    this->y = y;
}
boundaryPt(){}

};



class KCurvature{
public:
    boundaryPt* boundaryPtAry;
    int numPts;
    ifstream input;

KCurvature(char* inFile){
    input.open(inFile);
    input >> numPts;
    boundaryPtAry = new boundaryPt[numPts];
}

void loadData(char* inFile){
    input.open(inFile);
    int x;
    int y;

    while(!input.eof()){
        input >> x;
        input >> y;
        boundaryPtAry[index++] = new boundaryPt(x,y);
    }
};

我的问题是:

boundaryPtAry[index++] = new boundaryPt(x,y);

我正在尝试将我的boundaryPt 对象存储在我的boundaryPt 类型数组中,但由于我将该数组声明为boundaryPt*,它不会让我存储boundaryPt。

这是延迟指针的简单问题吗?我对 C++ 生疏了。

【问题讨论】:

  • boundaryPtAry[index].x = x; boundaryPtAry[index].y = y; index++; 怎么样?
  • 那行得通。我现在意识到,当我创建一个对象数组时,它实际上创建了实际的对象。所以甚至不需要创建一个新的边界点对象。谢谢!
  • @user5904091 请将您的答案作为答案发布,而不是更新问题本身。

标签: c++ arrays pointers object


【解决方案1】:

已解决!我现在意识到,在创建对象数组时,您不仅在创建数组,而且还创建了对象本身。所以没有必要创建一个新对象并尝试将它放入数组中(或者在我的情况下让数组索引指向它)。

while(!input.eof()){
    input >> boundaryPtAry[index].x;
    input >> boundaryPtAry[index].y;
    index++;
}

【讨论】:

  • 你来自 Java 背景吗?
  • 简短回答:是的。长答案:我是一名学生,直到本学期,我几乎所有的课程都分配了 Java 项目,所以我在 C++ 方面的经验比 Java 少得多。但我很高兴我今天学到了一些关于对象数组的新知识。
猜你喜欢
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
  • 2020-10-12
  • 2013-10-10
  • 1970-01-01
  • 2014-03-02
相关资源
最近更新 更多