0 / 0 / 0 Регистрация: 16.07.2016 Сообщений: 23 |
|
1 |
|
26.07.2016, 13:00. Показов 9511. Ответов 12
Доброго времени суток
0 |
257 / 234 / 185 Регистрация: 02.04.2016 Сообщений: 898 |
|
26.07.2016, 13:05 |
2 |
Кидай сюда код.
1 |
Модератор 13320 / 10454 / 6253 Регистрация: 18.12.2011 Сообщений: 27,910 |
|
26.07.2016, 13:09 |
3 |
1 |
INSIDERS 0 / 0 / 0 Регистрация: 16.07.2016 Сообщений: 23 |
||||
26.07.2016, 13:51 [ТС] |
4 |
|||
код очень большой
0 |
Объявлятель переменных 1220 / 406 / 320 Регистрация: 24.09.2011 Сообщений: 1,260 |
|
26.07.2016, 14:03 |
5 |
Пробовали тот же код с использованием
1 |
0 / 0 / 0 Регистрация: 16.07.2016 Сообщений: 23 |
|
26.07.2016, 14:11 [ТС] |
6 |
ну со switch я не пробовал
0 |
257 / 234 / 185 Регистрация: 02.04.2016 Сообщений: 898 |
|
26.07.2016, 14:15 |
7 |
Значит вы не перезагрузили operator<< и пытаетесь его использовать наверное…
1 |
0 / 0 / 0 Регистрация: 16.07.2016 Сообщений: 23 |
|
26.07.2016, 14:33 [ТС] |
8 |
то есть если я скопирую весь код пересоздам проект это поможет ?
0 |
257 / 234 / 185 Регистрация: 02.04.2016 Сообщений: 898 |
|
26.07.2016, 14:39 |
9 |
INSIDERS, Тогда бы так делали все программисты..
1 |
Объявлятель переменных 1220 / 406 / 320 Регистрация: 24.09.2011 Сообщений: 1,260 |
|
26.07.2016, 14:48 |
10 |
ошибка появляется во время компиляции Я честно пытался найти в приведённом выше коде 493 строку, но не преуспел.
1 |
0 / 0 / 0 Регистрация: 16.07.2016 Сообщений: 23 |
|
26.07.2016, 15:14 [ТС] |
11 |
я не программист пока что не те знания Добавлено через 2 минуты Добавлено через 20 минут
0 |
17457 / 9284 / 2269 Регистрация: 30.01.2014 Сообщений: 16,257 |
|
26.07.2016, 16:17 |
12 |
INSIDERS, кавычки внутри строки надо экранировать.
1 |
SpBerkut Объявлятель переменных 1220 / 406 / 320 Регистрация: 24.09.2011 Сообщений: 1,260 |
||||
26.07.2016, 16:26 |
13 |
|||
Если синтаксис подсветить, то всё становится очевидным.
1 |
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2088 |
Compiler Error C2088 |
11/04/2016 |
C2088 |
C2088 |
b93f7094-185b-423d-8bb9-507cd757dbf5 |
Compiler Error C2088
‘operator’ : illegal for ‘class-key’
The operator was not defined for the structure or union. This error is only valid for C code.
The following sample generates C2088 three times:
// C2088.c struct S { int m_i; } s; int main() { int i = s * 1; // C2088 struct S s2 = +s; // C2088 s++; // C2088 }
Here is my code where I try to access an element of class Edge
:
#include <iostream>
// for the sort()
#include <algorithm>
#define PI 3.14159265358979323846
struct Point{
Point(int xx, int yy): x(xx), y(yy) { }
int x;
int y;
};
// class Edge: representing lines segments of the poly-line
struct Edge{
// constructor
Edge(Point p0, Point p1) : start(p0), end(p1){
if (p0.x == p1.x && p0.y == p1.y) throw std::invalid_argument("Edge: Identical points!");
}
// operator< defined for the sorting by increasing ordinate of the end point
bool operator<(const Edge& e){ return (end.y < e.end.y); }
// data members: start point and end point of the line
Point start;
Point end;
};
static void generatePoints(vector<Point>& p){
p.push_back(Point(50,50));
p.push_back(Point(200,50));
p.push_back(Point(200,200));
p.push_back(Point(50,200));
}
//------------------------------------------------------------------------------------------------
int main(){
// Generate points for the poly-line
vector<Point> polyPoints;
generatePoints(polyPoints);
vector<Edge> polyEdges;
Point first = polyPoints(0);
Point last = polyPoints(polyPoints.size()-1);
polyEdges.push_back(Edge(last, first));
for (size_t i = 1; i < polyPoints.size(); ++i) polyEdges.push_back(Edge(polyPoints[i-1], polyPoints[i]));
int yCoordinate = polyEdges[i].end.y;
return 0;
}
Now, I have a vector of edges, like so:
vector<Edge> polyEdges;
and when I try to access it a specific member polyEdges[i].end.y
, I get the following error message:
'vector' : undeclared identifier
'Point' : illegal use of this type as an expression
see declaration of 'Point'
'p' : undeclared identifier
'generatePoints' : function-style initializer appears to be a function definition
vector' : undeclared identifier
see declaration of 'Point'
'polyPoints' : undeclared identifier
'Point' : illegal use of this type as an expression
'polyPoints' : undeclared identifier
'generatePoints': identifier not found
'vector' : undeclared identifier
Edge' : illegal use of this type as an expression
see declaration of 'Edge'
error C2088: '[' : illegal for class
polyEdges' : undeclared identifier
'polyPoints': identifier not found
'polyPoints' : undeclared identifier
left of '.size' must have class/struct/union
'Point' : illegal use of this type as an expression
error C2228: left of '.end' must have class/struct/union
error C2228: left of '.y' must have class/struct/union
It must be related with the overloading of the []operator
.
Question:
Should I overload [] operator
and if so, how to do it?
Here is my code where I try to access an element of class Edge
:
#include <iostream>
// for the sort()
#include <algorithm>
#define PI 3.14159265358979323846
struct Point{
Point(int xx, int yy): x(xx), y(yy) { }
int x;
int y;
};
// class Edge: representing lines segments of the poly-line
struct Edge{
// constructor
Edge(Point p0, Point p1) : start(p0), end(p1){
if (p0.x == p1.x && p0.y == p1.y) throw std::invalid_argument("Edge: Identical points!");
}
// operator< defined for the sorting by increasing ordinate of the end point
bool operator<(const Edge& e){ return (end.y < e.end.y); }
// data members: start point and end point of the line
Point start;
Point end;
};
static void generatePoints(vector<Point>& p){
p.push_back(Point(50,50));
p.push_back(Point(200,50));
p.push_back(Point(200,200));
p.push_back(Point(50,200));
}
//------------------------------------------------------------------------------------------------
int main(){
// Generate points for the poly-line
vector<Point> polyPoints;
generatePoints(polyPoints);
vector<Edge> polyEdges;
Point first = polyPoints(0);
Point last = polyPoints(polyPoints.size()-1);
polyEdges.push_back(Edge(last, first));
for (size_t i = 1; i < polyPoints.size(); ++i) polyEdges.push_back(Edge(polyPoints[i-1], polyPoints[i]));
int yCoordinate = polyEdges[i].end.y;
return 0;
}
Now, I have a vector of edges, like so:
vector<Edge> polyEdges;
and when I try to access it a specific member polyEdges[i].end.y
, I get the following error message:
'vector' : undeclared identifier
'Point' : illegal use of this type as an expression
see declaration of 'Point'
'p' : undeclared identifier
'generatePoints' : function-style initializer appears to be a function definition
vector' : undeclared identifier
see declaration of 'Point'
'polyPoints' : undeclared identifier
'Point' : illegal use of this type as an expression
'polyPoints' : undeclared identifier
'generatePoints': identifier not found
'vector' : undeclared identifier
Edge' : illegal use of this type as an expression
see declaration of 'Edge'
error C2088: '[' : illegal for class
polyEdges' : undeclared identifier
'polyPoints': identifier not found
'polyPoints' : undeclared identifier
left of '.size' must have class/struct/union
'Point' : illegal use of this type as an expression
error C2228: left of '.end' must have class/struct/union
error C2228: left of '.y' must have class/struct/union
It must be related with the overloading of the []operator
.
Question:
Should I overload [] operator
and if so, how to do it?
Итак, я только начинаю нелегкий путь в C++, так что решил сделать несложную программу: выдача вопросов и счет баллов за них. В суть углубляться не буду, но идея работы программы такая: в подключаемом файле я создаю и инициализирую двумерный вектор, каждый элемент которого строка с вопросом, так же я храню кол-во тем. Сейчас для примера будет 1 тема, но это не важно. Важно то, что при попытке сделать это получаю каскад ошибок, и вопрос: что я делаю не так и как это сделать лучше?
Код:
#ifndef QPACK1_H
#define QPACK1_H
int theme_amount = 1;
std::vector<std::vector<std::string> > questions(theme_amount + 1, std::vector<std::string>(6, " "));
questions[1][0] = "Вы попали на тему: Name of the themen" ; // сначала номер темы, потом номер вопроса(по 5), 0 вопрос - название темы.
questions[1][1] = "Question 1";
questions[1][2] = "Question 2";
questions[1][3] = "Question 3";
questions[1][4] = "Question 4";
questions[1][5] = "Question 5";
#endif
Список ошибок:
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(8,1): error C2466: невозможно выделить память для массива постоянного нулевого размера
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(8,17): error C2087: questions: отсутствует индекс
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(8,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(10,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(10,1): error C2040: questions: "int [1][1]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(11,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(11,1): error C2040: questions: "int [1][2]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(12,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(12,1): error C2040: questions: "int [1][3]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(13,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(13,1): error C2040: questions: "int [1][4]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(14,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(14,1): error C2040: questions: "int [1][5]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2CHGK_game.cpp(44,52): error C2088: [: недопустимо для class
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2CHGK_game.cpp(46,48): error C2088: [: недопустимо для class
Основной код программы:
#include <vector>
#include <iostream>
#include <string>
#include "qpack1.h" //список вопросов
struct players
{
std::vector<std::string> name;
std::vector<int> score;
};
int main()
{
int pl_amount, qst_number = 0;
players plist;
std::string input;
std::cout << "Enter number of players(less then 10): ";
std::cin >> pl_amount;
plist.name.resize(pl_amount);
plist.score.resize(pl_amount);
plist.score.assign(plist.score.size(), 0);
std::cout << "Enter players names: n";
for (int i = 0; i < pl_amount; i++)
std::cin >> plist.name[i];
std::cout << "Tips: enter stop to left the game. nUse + or - and number of player to give(take out) points to his score.n";
for (int theme_number = 1; theme_number <= theme_amount; theme_number++)
{
while (qst_number <= 4)
{
qst_number++;
if (qst_number == 1)
std::cout << questions[theme_number][0] << "n";
std::cout << questions[theme_number][qst_number] << "n";
TryAgain:
getline(std::cin, input);
if (input == "stop")
goto Results;
if(input.size() != 2 || !(input[1] > '0' && input[1] <= '9'))
{
std::cout << "Incorrect input.n";
goto TryAgain;
}
if(input[1] - '0' > pl_amount || input[1] - '0' <= 0)
{
std::cout << "Incorrect input(Player was not found).n";
goto TryAgain;
}
if (input[0] == '+')
{
plist.score[input[1] - '0' - 1] += qst_number * 10;
std::cout << plist.name[input[1] - '0' - 1] << " Gets + " << qst_number * 10 << " points!n";
}
else
if (input[0] == '-')
{
plist.score[input[1] - '0' - 1] -= qst_number * 10;
std::cout << plist.name[input[1] - '0' - 1] << " Gets - " << qst_number * 10 << " points!n";
}
else { std::cout << "Please start input with + or -.n";goto TryAgain; }
}
qst_number = 0;
}
Results:
std::cout << "The final score is: n";
for (int j = 0; j < pl_amount; j++)
std::cout << plist.name[j] << " : " << plist.score[j] << " points. n";
}
И еще есть проблема: при первом выводе темы и вопроса, сразу же после этого выводится Incorrect input, хотя ничего не было введено. (проверял заккоментив эту часть: )
questions[1][0] = «Вы попали на тему: Name of the themen» ; //
сначала номер темы, потом номер вопроса(по 5), 0 вопрос — название
темы.questions[1][1] = "Question 1"; questions[1][2] = "Question 2"; questions[1][3] = "Question 3"; questions[1][4] = "Question 4"; questions[1][5] = "Question 5";
В общем, как фиксить?)
Я изучаю шаблоны C ++, и у меня есть функция для различных типов карт:
template<typename T> void foo(T m1, T m2){ //map m1 and map m2
map<pair<T, int>, int>::iterator itr1 = m1.begin();
map<pair<T, int>, int>::iterator itr2 = m2.begin();
while (itr1 != m1.end() && itr2 != m2.end()){
//do something with itr1 and itr2
}
}
Когда я компилирую его в VS2013, я получил ошибку: error C2088: '!=' : illegal for class
что указывает на while (itr1 != m1.end() && itr2 != m2.end())
, Но если я явно объявляю тип карт (то есть не использую шаблон), у меня нет ошибки. Кто-нибудь может сказать мне, что я здесь делаю не так? Спасибо!
-3
Решение
std::map<pair<T, int>, int>::iterator
является итератором с карты, тип ключа которого pair<T, int>
(где T
по-видимому, также map
в вашем примере) и какой тип значения int
, который явно отличается от typename T::iterator
который является типом m1.begin()
, Что вы, вероятно, хотите, это:
template<typename T>
void foo(T m1, T m2) {
typename T::iterator itr1 = m1.begin();
/* ... */
}
Или же:
template <typename T>
void foo(std::map<std::pair<T, int>, int> m1,
std::map<std::pair<T, int>, int> m2) {
typename T::iterator itr1 = m1.begin();
/* ... */
}
В первом случае параметр шаблона является типом map
(T = std::map<std::pair<T, int>>
) в то время как во втором случае это тип первого атрибута ключа карты.
2
Другие решения
Других решений пока нет …
Итак, я только начинаю нелегкий путь в C++, так что решил сделать несложную программу: выдача вопросов и счет баллов за них. В суть углубляться не буду, но идея работы программы такая: в подключаемом файле я создаю и инициализирую двумерный вектор, каждый элемент которого строка с вопросом, так же я храню кол-во тем. Сейчас для примера будет 1 тема, но это не важно. Важно то, что при попытке сделать это получаю каскад ошибок, и вопрос: что я делаю не так и как это сделать лучше?
Код:
#ifndef QPACK1_H
#define QPACK1_H
int theme_amount = 1;
std::vector<std::vector<std::string> > questions(theme_amount + 1, std::vector<std::string>(6, " "));
questions[1][0] = "Вы попали на тему: Name of the themen" ; // сначала номер темы, потом номер вопроса(по 5), 0 вопрос - название темы.
questions[1][1] = "Question 1";
questions[1][2] = "Question 2";
questions[1][3] = "Question 3";
questions[1][4] = "Question 4";
questions[1][5] = "Question 5";
#endif
Список ошибок:
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(8,1): error C2466: невозможно выделить память для массива постоянного нулевого размера
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(8,17): error C2087: questions: отсутствует индекс
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(8,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(10,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(10,1): error C2040: questions: "int [1][1]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(11,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(11,1): error C2040: questions: "int [1][2]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(12,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(12,1): error C2040: questions: "int [1][3]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(13,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(13,1): error C2040: questions: "int [1][4]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(14,19): error C4430: отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2qpack1.h(14,1): error C2040: questions: "int [1][5]" отличается по уровням косвенного обращения от "std::vector<std::vector<std::string,std::allocator<std::string>>,std::allocator<std::vector<std::string,std::allocator<std::string>>>>"
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2CHGK_game.cpp(44,52): error C2088: [: недопустимо для class
1>C:UsersUsersourcereposConsoleApplication2ConsoleApplication2CHGK_game.cpp(46,48): error C2088: [: недопустимо для class
Основной код программы:
#include <vector>
#include <iostream>
#include <string>
#include "qpack1.h" //список вопросов
struct players
{
std::vector<std::string> name;
std::vector<int> score;
};
int main()
{
int pl_amount, qst_number = 0;
players plist;
std::string input;
std::cout << "Enter number of players(less then 10): ";
std::cin >> pl_amount;
plist.name.resize(pl_amount);
plist.score.resize(pl_amount);
plist.score.assign(plist.score.size(), 0);
std::cout << "Enter players names: n";
for (int i = 0; i < pl_amount; i++)
std::cin >> plist.name[i];
std::cout << "Tips: enter stop to left the game. nUse + or - and number of player to give(take out) points to his score.n";
for (int theme_number = 1; theme_number <= theme_amount; theme_number++)
{
while (qst_number <= 4)
{
qst_number++;
if (qst_number == 1)
std::cout << questions[theme_number][0] << "n";
std::cout << questions[theme_number][qst_number] << "n";
TryAgain:
getline(std::cin, input);
if (input == "stop")
goto Results;
if(input.size() != 2 || !(input[1] > '0' && input[1] <= '9'))
{
std::cout << "Incorrect input.n";
goto TryAgain;
}
if(input[1] - '0' > pl_amount || input[1] - '0' <= 0)
{
std::cout << "Incorrect input(Player was not found).n";
goto TryAgain;
}
if (input[0] == '+')
{
plist.score[input[1] - '0' - 1] += qst_number * 10;
std::cout << plist.name[input[1] - '0' - 1] << " Gets + " << qst_number * 10 << " points!n";
}
else
if (input[0] == '-')
{
plist.score[input[1] - '0' - 1] -= qst_number * 10;
std::cout << plist.name[input[1] - '0' - 1] << " Gets - " << qst_number * 10 << " points!n";
}
else { std::cout << "Please start input with + or -.n";goto TryAgain; }
}
qst_number = 0;
}
Results:
std::cout << "The final score is: n";
for (int j = 0; j < pl_amount; j++)
std::cout << plist.name[j] << " : " << plist.score[j] << " points. n";
}
И еще есть проблема: при первом выводе темы и вопроса, сразу же после этого выводится Incorrect input, хотя ничего не было введено. (проверял заккоментив эту часть: )
questions[1][0] = «Вы попали на тему: Name of the themen» ; //
сначала номер темы, потом номер вопроса(по 5), 0 вопрос — название
темы.questions[1][1] = "Question 1"; questions[1][2] = "Question 2"; questions[1][3] = "Question 3"; questions[1][4] = "Question 4"; questions[1][5] = "Question 5";
В общем, как фиксить?)