【问题标题】:passing pointers through multiple functions from main() C++从 main() C++ 通过多个函数传递指针
【发布时间】:2015-08-05 04:48:10
【问题描述】:

这不太行得通。让我们看看我们是否可以共同扩展我们在这方面的知识。好的:

vector<vector<Point>> aVectorOfPoints
int main(){
    someConstructor(&aVectorOfPoints)
}

someConstructor(vector<vector<Point>>* aVectorOfPoints){
    functionOne(aVectorOfPOints);
}

functionOne(vector<vector<Point>>* aVectorOfPOints){
    aVectorOfPoints[i][j] = getPointFromClass();
}
//functionX(...){...}

我在 functionOne 的赋值下遇到了一些错误。我怎样才能更好地做到这一点?谢谢。

具体错误是“没有运算符'='匹配这些操作数”。

【问题讨论】:

  • Point 是如何定义的?
  • @RSahu 它被定义为标准点。我实际上是从构造函数中得到这一点并将其放在向量本身中。这将在课堂之外使用。
  • 错误?什么样的错误?编译器错误?
  • @elimad 没有运算符 '=' 与这些操作数匹配。

标签: c++ pointers constructor main


【解决方案1】:

为什么会这样?

aVectorOfPoints[i][j] = getPointFromClass();

aVectorOfPoints 的类型是 vector&lt;vector&lt;Point&gt;&gt;*
aVectorOfPoints[i] 的类型是 vector&lt;vector&lt;Point&gt;&gt;
aVectorOfPoints[i][j] 的类型是 vector&lt;Point&gt;

Point 不能分配给 vector&lt;Point&gt;。因此编译器错误。

也许你打算使用:

(*aVectorOfPoints)[i][j] = getPointFromClass();

您可以通过传递引用来简化代码。

int main(){
    someConstructor(aVectorOfPoints)
}

someConstructor(vector<vector<Point>>& aVectorOfPoints){
    functionOne(aVectorOfPOints);
}

functionOne(vector<vector<Point>>& aVectorOfPOints){
    aVectorOfPoints[i][j] = getPointFromClass();
}

【讨论】:

  • 感谢传递参考效果更好。传指针和解引用路由有什么好处吗?
  • @hownowbrowncow 不,更糟。使用参考文献
【解决方案2】:

使用引用而不是指针:

someConstructor( vector<vector<Point>> &aVectorOfPoints) {

functionOne 也是如此。

您的错误是aVectorOfPoints[i]i 索引指针。如果使用指针,您需要先取消引用指针,然后再写 (*aVectorOfPoints)[i][j]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 2011-07-12
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    相关资源
    最近更新 更多