0

所以我有一个类 Coord,它是一个屏幕位置 (x, y) 和一个类 Grid,它应该是一个由 13 个这些坐标组成的数组,从文本文件中读取。我遇到的错误是错误 C2512: 'Coord' : 没有合适的默认构造函数可用 grid.h 26 虽然我有 Coord.h 的两个构造函数,但我认为它会使用输入流之一?有点从其他来源的点点滴滴和同时学习,所以如果我忽略了一些明显的东西,请原谅我。

坐标.h

# pragma once

// class for whole screen positions

#include "DarkGDK.h"
#include <istream>

using std::istream;

class Coord
{
    float cx, cy;

    public:
        Coord(float x, float y) : cx(x), cy(y) {} //set components directly
        Coord(istream& input); //set from input

        float x()
        {
            return cx;
        }
        float y()
        {
            return cy;
        }

        Coord operator+(const Coord& c);
};

Coord::Coord(istream& input)
{
    input >> cx >> cy;
}

Coord Coord::operator+(const Coord& c)
{
    return Coord(cx+c.cx, cy+c.cy);
}

网格.h

# pragma once

// class for the grid array

#include "DarkGDK.h"
#include "Coord.h"
#include <fstream>
#include <iostream>

using namespace std;

const int N = 13;
const char filename[] = "grid.txt";

class Grid
{
    Coord gridpos[N];

    public:
        Grid();
        void FillGrid(); //read-in coord values
};

Grid::Grid()
{
    FillGrid();
}

void Grid::FillGrid()
{
    int i;

    ifstream filein(filename, ios::in); //file for reading

    for(i=0; !filein.eof(); i++)
    {
        filein >> gridpos[i].x >> gridpos[i].y; //read in
        filein.close();
    }
}

任何帮助表示赞赏,谢谢。

4

1 回答 1

1

您的代码中有许多小错误。这是一个适用于一些注释的版本。

#include <fstream>
#include <iostream>

using namespace std;

const int N = 13;
const char filename[] = "grid.txt";

class Coord
{
    float cx, cy;

    public:
        // Default constructor required to declare array: eg Coord c[23];
        Coord() : cx(0), cy(0)
        {}

        Coord(float x, float y) : cx(x), cy(y) 
        {}
        // You were returning float instead of float& which means you could not update
        float& x()
        {
            return cx;
        }

        float& y()
        {
            return cy;
        }

        Coord Coord::operator+(const Coord& c)
        {
            return Coord(cx+c.cx, cy+c.cy);
        }

        friend istream& operator>>(istream& input, Coord& rhs)
        {
            input >> rhs.cx >> rhs.cy;
            return input;
        }
};


class Grid
{
    Coord gridpos[N];

    public:
        Grid()
        {
            FillGrid();
        }

        void FillGrid()
        {
            int i;

            ifstream filein(filename, ios::in); //file for reading

            for(i=0; !filein.eof(); i++)
            {
                filein >> gridpos[i];
            }
               // Close the file after you have finished reading from it
            filein.close();
        }
};


int main()
{
    Grid g;
    return 0;
}
于 2013-04-27T00:16:37.660 回答