【问题标题】:Pointer Passing and Parameters指针传递和参数
【发布时间】:2015-03-22 15:57:50
【问题描述】:

我的代码现在有问题。我似乎无法得到我需要的东西并返回我的结构“b”的地址,以便其他函数可以使用它。如果你能帮助我,那就太好了!

这是我需要的代码:

    int notFound = 0;
int choiceNumber;
int arraySize;
Basketball * b;



b = readFile(arraySize, notFound, &b);

这是我遇到问题的功能:

Basketball * readFile(int & arraySize, int & notFound, Basketball * &b)
{
    ifstream inputFile;
    inputFile.open("games.txt");
if(inputFile.fail())
{
    cout << "The file name \"games.txt\" was not found!" << endl;
    notFound = 1;
}
else
{
    inputFile >> arraySize;

    b = new Basketball [arraySize];

    for (int i = 0; i < arraySize; i++)
    {
        inputFile >> b[i].visitTeam >> b[i].homeScore >> b[i].visitScore;
    }

    return & b;
}

}

我的构建错误是:

Error: invalid intialization of non-const reference of type basketball*& from an rvalue of type Basketball**
Error: In passing arguement 3 of Basketball* readfile(int&,int&, Basketball*&)
Error: Cannot convert Basketball** to Basketball* in return

如果你能指出我正确的方向,那就太好了!

【问题讨论】:

  • 你不需要“return & b;”中的 &这只是创建一个指向您的指针的指针。试试“return b;”
  • @jamolnng 修复了第三个错误。前两个是怎么回事?
  • 好吧,在第一个中,您再次创建了指向指针的指针,所以这个 readFile(arraySize, notFound, &b);您应该在 b 之前删除 &。
  • 请让你的标题描述问题,而不是仅仅列出两个广泛的编程主题。

标签: c++ pointers parameter-passing return-value


【解决方案1】:

变量b 已经是一个指针,使用&amp;b 将创建一个指向该指针的指针。删除地址运算符&amp;

错误消息非常很清楚,当你声明只返回一个指针时,你返回一个指向指针的指针也是如此。

【讨论】:

    【解决方案2】:

    "返回 b;"是你想要的,而不是“return &b”

    &b 是 Basketball* 的地址,所以你会以不正确的 Basketbal** 结尾

    【讨论】:

      【解决方案3】:

      正如其他人已经写的那样,由于b 已经是一个指针,return b; 将修复您的错误。

      如果您执行return &amp;b;,您将返回一个指针的地址,即一个“双层间接” 指针,这将是一个Basketball**

      不过,让我补充一点,您可以使用更现代的习语来简化您的 C++ 代码,例如使用 std::vector&lt;Basketball&gt; 代替原始指针和原始数组,例如:

      std::vector<Basketball> readFile(int & notFound);
      

      请注意,vector 知道自己的大小(例如,您可以调用其 size() 方法来查询它),因此您不需要单独的引用参数来存储大小。

      此外,vector 自动 清理其内容,这要归功于它的析构函数。因此,您不必给调用者带来负担,即显式调用delete[] 以释放分配的数组。

      作为替代方案,您可以使用 bool 参数,意思是“未找到”,并将向量作为非常量引用传递,例如:

      // Returns false if not found, true if found
      bool readFile(std::vector<Basketball>& v);
      

      或者,根据您的设计,您甚至可以返回 std::vector,并在未找到的情况下抛出异常。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 2021-04-08
        • 2012-05-03
        • 2015-06-16
        • 2012-01-24
        • 1970-01-01
        • 2011-10-07
        相关资源
        最近更新 更多