指针传递和参数

时间:2015-03-22 15:57:50

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

我的代码现在有问题。我似乎无法得到我需要的东西并返回我的结构“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

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

3 个答案:

答案 0 :(得分:2)

变量b已经是指针,使用&b将创建指向指针的指针。删除地址操作符&

错误消息是非常清除它,当你声明只返回一个指针时返回一个指针指针。

答案 1 :(得分:1)

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

&amp; b是篮球*的地址,所以你最终会得到错误的篮球**

答案 2 :(得分:1)

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

如果执行return &b;,则返回指针的地址,即“双级间接”指针,这将是{{1 }}

但是,让我补充一点,您可以使用更现代的习惯用法来简化您的C ++代码,例如使用Basketball**而不是原始指针和原始数组,例如:

std::vector<Basketball>

请注意,std::vector<Basketball> readFile(int & notFound); 知道自己的大小(例如,您可以调用其vector方法来查询它),因此您不需要单独的引用参数来存储大小。

而且,由于其析构函数,size() 会自动清理其内容。因此,您不会给调用者带来任何负担,以显式调用vector来释放已分配的数组。

作为替代方案,您可以使用delete[]参数表示“未找到”,并将该向量作为非const引用传递,例如:

bool

或者,根据您的设计,您甚至可以返回// Returns false if not found, true if found bool readFile(std::vector<Basketball>& v); ,并在未找到的情况下抛出异常。

相关问题