VS 2008 c++对象数组

VS 2008 C++ object array

本文关键字:数组 对象 c++ 2008 VS      更新时间:2023-10-16

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

Coord.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);
}

Grid.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();
    }
}

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

#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;
}