在c++的main()函数中传递指针

passing pointers through multiple functions from main() C++

本文关键字:指针 函数 c++ main      更新时间:2023-10-16

这不是很好。让我们看看我们是否可以共同扩展我们对这个问题的认识。好:

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的赋值下面得到一些错误。我怎样才能做得更好?谢谢。

具体错误是"No operator '='匹配这些操作数"

为什么这是错误的?

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

类型的aVectorOfPointsvector<vector<Point>>*
aVectorOfPoints[i]类型为vector<vector<Point>>
aVectorOfPoints[i][j]的类型为vector<Point>

Point不能分配给vector<Point>。因此会出现编译错误。

也许你想用:

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

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

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

使用引用代替指针:

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

functionOne相同。

你的错误是aVectorOfPoints[i]通过i索引指针。如果使用指针,在此之前需要先对指针解引用,写入(*aVectorOfPoints)[i][j] .