【问题标题】:c++ error: expected primary-expression before '&' tokenc++ 错误:“&”标记之前的预期主表达式
【发布时间】:2016-09-03 22:04:53
【问题描述】:

我正在学习 c++,并且我有以下代码在第 39 行(fill_file() 调用)中给出错误。我在网上搜索了解决方案,但找不到为什么会出现此错误(预期的主表达式在 '&' 标记之前)。

#include <iostream>
#include <string>
#include <vector>
#include "../std_lib_facilities.h"
using namespace std;

struct Point {
    double x;
    double y;
};

void fill_file(vector<Point>& original_points) {
    string outputfile="mydata.txt";
    ofstream ost{outputfile};
    if(!ost) error("Can't open outputfile ", outputfile);
    for(int i=0;i<original_points.size();i++) {
        ost << original_points[i].x << " " << original_points[i].y << endl;
    }
}

int main() {
    cout << "Please enter 3 points with a value: " << endl;
    vector<Point> original_points;
    Point p;
    double x;
    double y;
    for(int i=0;i<3;i++) {
        cin>>p.x;
        cin>>p.y;
        original_points.push_back(p);
    }
    cout << endl;
    cout << endl << "Points: " << endl;
    for(int i=0;i<original_points.size();i++) {
        cout << original_points[i].x << " " << original_points[i].y << endl;
        /* ost << original_points[i].x << " " << original_points[i].y << endl; */
    }
    cout << endl << endl;
    fill_file(vector<Point>& original_points);
    return 0;
}

我做错了什么?谢谢帮忙!!

【问题讨论】:

  • 只是fill_file(original_points);

标签: c++


【解决方案1】:

你在调用你的 fill_file 函数时犯了一个错误:

fill_file(vector<Point>& original_points);

必须这样调用:

fill_file(original_points);

【讨论】:

    【解决方案2】:

    调用函数fill_file() 时出错。目前你这样称呼它:

    fill_file(vector<Point>& original_points);
    

    以上,我认为是复制粘贴错误。我想做的是:

    fill_file(original_points);
    

    因为original_points 是实际变量,而不是vector&lt;Point&gt;&amp; original_points。正如您的错误所述:

    '&' 标记之前的预期主表达式

    如上所示,您在函数调用中放置了一个随机左值,这是不允许的。

    【讨论】:

    • 是的,我还是个新手。我现在明白了:不要在函数的调用中(仅在声明和定义中)使用参数的类型。
    • 如果您认为正确,请标记答案。
    • 以上答案是正确的。如何标记/标记答案正确?
    • 点击向下箭头下方的绿色复选标记图标。
    • 我在向下箭头下方看不到绿色复选标记图标,只有一个灰色星标将问题标记为最喜欢的问题。
    猜你喜欢
    • 2015-03-31
    • 2012-07-08
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 2013-01-13
    • 2017-09-24
    相关资源
    最近更新 更多