Учу C++ по книге, в конце главы есть задания и одно из них — сделать функцию подсчета символов в классе Document. При создании класса возникла проблема: при запуске программы появляется ошибка «C3646 begin: неизвестный спецификатор определения». Такая же ошибка с функцией end();
document.h:
#include <list>
#include <vector>
#include <iostream>
using namespace std;
using Line = vector<char>;
struct Document {
list<Line> line;
Document() { line.push_back(Line{}); }
Text_iterator begin() { return Text_iterator(line.begin(), line.begin()->begin()); } //здесь ошибка
Text_iterator end() { return Text_iterator(line.end(), line.end()->end()); } //в этой строке так же
int count();
};
istream& operator>> (istream& is, Document& d) {
for (char ch; is.get(ch);) {
d.line.back().push_back(ch);
if (ch == 'n') d.line.push_back(Line{});
}
if (d.line.back().size()) d.line.push_back(Line{});
return is;
}
class Text_iterator {
list<Line>::iterator ln;
Line::iterator pos;
public:
Text_iterator (list<Line>::iterator ll, Line::iterator pp) : ln{ll}, pos{pp} {}
char& operator* () { return *pos; }
Text_iterator& operator++ ();
bool operator== (const Text_iterator& other) const { return ln == other.ln && pos == other.pos; }
bool operator!= (const Text_iterator& other) const { return !(*this == other); }
};
задан 20 авг 2017 в 13:58
Ну откуда же компилятору знать, что такое Text_iterator
до его объявления?
Перенесите объявление класса Text_iterator
перед классом Document
.
Ответил только на ваш конкретный вопрос; верно ли все у вас будет после этого работать — не проверял…
ответ дан 20 авг 2017 в 14:06
HarryHarry
215k15 золотых знаков117 серебряных знаков228 бронзовых знаков
1
I’m trying to code a simple DirectX11 engine but I keep getting this strange error and I can’t find the problem: I define a Terrain class and a Mesh class and #include the Mesh class in the Terrain class:
the Terrain class definition:
// Terrain.h
#pragma once
#include "Noise.h"
#include "Mesh.h"
class Terrain
{
public:
Terrain(float width, float depth, int numVerticesW, int numVerticesD);
~Terrain();
float GetHeight(float x, float z);
void Draw();
private:
Mesh mMesh; // I get the error on this line
Noise mNoiseGenerator;
std::vector<float> mHeights;
void CreateTerrain(float width, float depth, int numVerticesW, int numVerticesD);
float ComputeHeight(float x, float z, float startFrequency, float startAmplitude, float persistence, int octaves);
};
and the Mesh class definition:
// Mesh.h
#pragma once
#include <d3d11.h>
#include <vector>
#include "Game.h"
class Mesh
{
public:
Mesh();
~Mesh();
template <typename T, unsigned int N>
void LoadVertexBuffer(T data[][N], unsigned int size, bool dynamic = false);
void LoadIndexBuffer(std::vector<unsigned int> indices);
void SetVertexCount(unsigned int vertexCount);
void Bind();
void Draw();
private:
std::vector<ID3D11Buffer*> mVertexBuffers;
std::vector<unsigned int> mStrides;
ID3D11Buffer *mIndexBuffer;
unsigned int mVertexCount;
};
template <typename T, unsigned int N>
void Mesh::LoadVertexBuffer(T data[][N], unsigned int size, bool dynamic)
{
D3D11_BUFFER_DESC bufferDesc = {};
bufferDesc.Usage = dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_IMMUTABLE;
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.ByteWidth = sizeof(T[N]) * size;
bufferDesc.CPUAccessFlags = dynamic ? D3D11_CPU_ACCESS_WRITE : 0;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA bufferData = {};
bufferData.pSysMem = data;
ID3D11Buffer *buffer;
Game::GetInstance()->GetDevice()->CreateBuffer(&bufferDesc, &bufferData, &buffer);
mVertexBuffers.push_back(buffer);
mStrides.push_back(sizeof(T[N]));
}
When I compile the code I get:
Severity Code Description Project File Line Suppression State
Error C3646 'mMesh': unknown override specifier DirectX11 engine 0.3 c:userslucadesktopprogrammingcodec++sourcevisual studiodirectx11 engine 0.3terrain.h 14
Severity Code Description Project File Line Suppression State
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int DirectX11 engine 0.3 c:userslucadesktopprogrammingcodec++sourcevisual studiodirectx11 engine 0.3terrain.h 14
I searched the web but most results show missing semicolons or circular inclusion issues but I can’t find any.
EDIT
I found the issue but I can’t explain why my solution works:
following the inclusion tree:
Terrain.h —> Mesh.h —> Game.h —> Renderer.h —> Terrain.h
eliminating #include «Terrain.h» (since I just declare Terrain * pointers inside the class) and adding it to Terrain.cpp seems to solve the issue.
So it must be a matter of circular inclusion, but shouldn’t I be guarded against that by using header/include guards?
SadiQ228 -4 / 24 / 7 Регистрация: 16.12.2016 Сообщений: 716 |
||||
1 |
||||
23.07.2018, 00:22. Показов 6385. Ответов 2 Метки нет (Все метки)
подчеркивает строку где объявляется переменная string не понимаю в чем дело
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
23.07.2018, 00:22 |
2 |
lArtl 322 / 174 / 78 Регистрация: 09.10.2014 Сообщений: 809 |
||||
23.07.2018, 03:06 |
2 |
|||
выше напиши
0 |
-4 / 24 / 7 Регистрация: 16.12.2016 Сообщений: 716 |
|
23.07.2018, 03:07 [ТС] |
3 |
разобрался не везде подрубил инклуды
0 |
Я пытаюсь написать простой движок DirectX11, но продолжаю получать эту странную ошибку и не могу найти проблему: я определяю класс Terrain и класс Mesh и #include класс Mesh в классе Terrain:
определение класса Terrain:
// Terrain.h
#pragma once
#include "Noise.h"#include "Mesh.h"
class Terrain
{
public:
Terrain(float width, float depth, int numVerticesW, int numVerticesD);
~Terrain();
float GetHeight(float x, float z);
void Draw();
private:
Mesh mMesh; // I get the error on this line
Noise mNoiseGenerator;
std::vector<float> mHeights;
void CreateTerrain(float width, float depth, int numVerticesW, int numVerticesD);
float ComputeHeight(float x, float z, float startFrequency, float startAmplitude, float persistence, int octaves);
};
и определение класса Mesh:
// Mesh.h
#pragma once
#include <d3d11.h>
#include <vector>
#include "Game.h"
class Mesh
{
public:
Mesh();
~Mesh();
template <typename T, unsigned int N>
void LoadVertexBuffer(T data[][N], unsigned int size, bool dynamic = false);
void LoadIndexBuffer(std::vector<unsigned int> indices);
void SetVertexCount(unsigned int vertexCount);
void Bind();
void Draw();
private:
std::vector<ID3D11Buffer*> mVertexBuffers;
std::vector<unsigned int> mStrides;
ID3D11Buffer *mIndexBuffer;
unsigned int mVertexCount;
};template <typename T, unsigned int N>
void Mesh::LoadVertexBuffer(T data[][N], unsigned int size, bool dynamic)
{
D3D11_BUFFER_DESC bufferDesc = {};
bufferDesc.Usage = dynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_IMMUTABLE;
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.ByteWidth = sizeof(T[N]) * size;
bufferDesc.CPUAccessFlags = dynamic ? D3D11_CPU_ACCESS_WRITE : 0;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA bufferData = {};
bufferData.pSysMem = data;
ID3D11Buffer *buffer;
Game::GetInstance()->GetDevice()->CreateBuffer(&bufferDesc, &bufferData, &buffer);
mVertexBuffers.push_back(buffer);
mStrides.push_back(sizeof(T[N]));
}
Когда я компилирую код, я получаю:
Severity Code Description Project File Line Suppression State
Error C3646 'mMesh': unknown override specifier DirectX11 engine 0.3 c:userslucadesktopprogrammingcodec++sourcevisual studiodirectx11 engine 0.3terrain.h 14
Severity Code Description Project File Line Suppression State
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int DirectX11 engine 0.3 c:userslucadesktopprogrammingcodec++sourcevisual studiodirectx11 engine 0.3terrain.h 14
Я искал в Интернете, но большинство результатов показывают пропущенные точки с запятой или циклические проблемы с включением, но я не могу их найти.
РЕДАКТИРОВАТЬ
Я обнаружил проблему, но не могу объяснить, почему мое решение работает:
следуя дереву включения:
Terrain.h -> Mesh.h -> Game.h -> Renderer.h -> Terrain.h
устранение #include «Terrain.h» (поскольку я просто объявляю указатели Terrain * внутри класса) и добавление его в Terrain.cpp, похоже, решает проблему.
Так что, должно быть, речь идет о круговом включении, но разве я не должен быть защищен от этого с помощью защиты заголовка / включения?
1
Решение
Ваша проблема в том, что #pragma once
предотвращает только двойное включение. То есть это делает следующее безопасным (упрощенным, чтобы сделать это очевидным):
// Terrain.cpp
#include "Terrain.h"#include "Terrain.h"
Это не решает круговое включение, которое гораздо сложнее решить автоматически. С двойным включением понятно, кто из них первый. Но у круга нет начала.
2
Другие решения
Других решений пока нет …
Solution 1
This is just another Microsoft cock-up. Here it is in essence:
class C
{
x y ;
} ;
If you submit this to a sensible compiler like g++, it gives you a helpful error message:
3:2: error: ‘x’ does not name a type
MSVC, on the other hand, comes up with this gibberish:
(3): error C3646: ‘y’: unknown override specifier
(3): error C4430: missing type specifier — int assumed. Note: C++ does not
support default-int
With this key, you can decrypt Microsoft’s error message into:
error: ‘Matrix4x4’ does not name a type
Solution 2
The error is most likely because that TransformHierarchy
and Matrix4x4
are not defined.
If they are not defined in "assert.h"
and "vec3f.h"
, this should be the case.
Forward declaration is enough only when you use the reference types and/or pointer types only. Therefore, to forward declare Triangle
is OK. But forward declare Triangle
does not mean your shape.h
is processed. Neither does your material.h
which is included in shape.h
.
Therefore, all names in material.h
is not visible from this code.
TransformHierarchy
and Matrix4x4
are not recognized by the compiler.
Many of the compliers will complain with words similar to "missing type specifier - int assumed"
Solution 3
In my case, it was found that a header file had the following directives for a class [ie, myComboBoxData]
#ifndef __COMBOBOXDATA__
#define __COMBOBOXDATA__
// ...
class myComboBoxData
{
// ...
}
#endif
As another class below tried to use myComboBoxData
class
class TypeDlg : public CDialog
{
myComboBoxData cbRow,cbCol;
// ...
}
the error message popped up as above:
«error C3646: ‘cbRow’: unknown override specifier».
Solution:
The problem was the directive name (__COMBOBOXDATA__
) was already used by OTHER header.
Thus, make sure to use some other name like (__myCOMBOBOXDATA__
).
Related videos on Youtube
03 : 33
Undefined and uninitialized variables (C++ programming tutorial)
05 : 58
Understanding errors and how to fix them
02 : 54
Error: requires a type specifier for all declarations, return type of out of line definition of
Legendary Computer Programmer
07 : 06
Cách sửa lỗi gcc is not recognized as internal or extermal command trên VSC
03 : 23
02 : 37
05 : 44
C compilation Error: undefined reference to
04 : 03
Runtime Error r6025 In Visual C++ (Skyrim & Fallout) FIX
06 : 25
Hướng dẫn fix»Microsoft Visual C++ Runtime Library»- fix»Microsoft Visual C++ Runtime Library Error»
Comments
-
I modified my project and after compiling there pop up some weird error.
#ifndef BART_RAY_TRACER_MESH_H #define BART_RAY_TRACER_MESH_H #include <vector> #include "assert.h" #include "vec3f.h" class Triangle; class Mesh { public: uint32_t nverts; bool _is_static; vec3f *verts; vec3f *_verts_world; Material material; // 2 error occurs at the line below Matrix4x4 _trans_local_to_world; // '_trans_local_to_world': unknown override specifier & missing type specifier - int assumed. Note: C++ does not support default-int Matrix4x4 _trans_local_to_world_inv; TransformHierarchy *_trans_hierarchy; std::vector<Triangle* > triangles; // ... }; #endif
When I change the order of the declaration a little bit, the error always occurs the line after
Material material
, but with different message:#ifndef BART_RAY_TRACER_MESH_H #define BART_RAY_TRACER_MESH_H #include <vector> #include "assert.h" #include "vec3f.h" class Triangle; class Mesh { public: uint32_t nverts; bool _is_static; vec3f *verts; vec3f *_verts_world; Material material; // 2 error occurs at the line below TransformHierarchy *_trans_hierarchy; // error C2143: syntax error: missing ';' before '*' & error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Matrix4x4 _trans_local_to_world; Matrix4x4 _trans_local_to_world_inv; std::vector<Triangle* > triangles; // ... }; #endif
I’ve searched for similar questions on SO but none seems useful.
I’ve checked myvec3f
,Triangle
class definition in case there are missing semicolons but I can’t find any.Can any one help?
-
Where is Material defined?
-
Based on the errors, it sounds like neither
Matrix4x4
norTransformHierarchy
are declared yet. You may be missing includes for both.
-