VS 2008 c++对象数组
VS 2008 C++ object array
所以我有一个类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;
}
相关文章:
- 销毁C++中动态分配的内存(数组对象)
- 数组对象的生存期是否在重用其元素存储时结束?
- 为什么顶点数组对象会导致错误?
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- OpenGL 顶点数组对象与 tinyobjloader
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- C++ RapidJson 帮助反序列化数组对象
- ptrdiff_t可以表示指向同一数组对象元素的指针的所有减法吗?
- 检查成员函数是否返回临时对象或数组对象
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 如何使用箭头指针打印出一类数组对象,这些对象中有多个分数
- C++17 std::shared_ptr<> 类数组对象的重载运算符 []
- 添加两个具有运算符重载的数组对象,从而导致分段错误
- opengl:两个不同的矢量可以绑定到同一个顶点数组对象吗
- 使用相同的数据填充数组对象或使用指针
- 方法用于最快的分配,并且不需要将动态大小的数组对象作为局部变量
- 如何将2d数组对象传递给c++中的函数
- ReferenceTable溢出(jni-android),数组对象释放