Error c2976 std vector слишком мало аргументов шаблон

I am getting following errors when trying to compile a c++ file in Visual Studio 2019. The developer who built the software says this used to work on Visual Studio 2012. I get the following error:

I am getting following errors when trying to compile a c++ file in Visual Studio 2019. The developer who built the software says this used to work on Visual Studio 2012.

I get the following error:

Severity    Code    Description Project File    Line    Suppression State
Error   C2976   'std::array': too few template arguments    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 45  
Error   C3699   '^': cannot use this indirection on type 'std::array'   CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 45  
Error   C2976   'std::array': too few template arguments    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 45  
Error   C2027   use of undefined type 'std::array'  CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 45  
Error   C2976   'std::array': too few template arguments    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 46  
Error   C3699   '^': cannot use this indirection on type 'std::array'   CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 46  
Error   C2976   'std::array': too few template arguments    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 46  
Error   C2027   use of undefined type 'std::array'  CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 46  
Error   C2976   'std::array': too few template arguments    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 47  
Error   C3699   '^': cannot use this indirection on type 'std::array'   CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 47  
Error   C2976   'std::array': too few template arguments    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 47  
Error   C2027   use of undefined type 'std::array'  CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 47  
Error   C2976   'std::array': too few template arguments    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 49  
Error   C3699   '^': cannot use this indirection on type 'std::array'   CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 49  
Error   C2976   'std::array': too few template arguments    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 49  
Error   C2027   use of undefined type 'std::array'  CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 49  
Error   C2976   'std::array': too few template arguments    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 50  
Error   C3699   '^': cannot use this indirection on type 'std::array'   CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 50  
Error   C2976   'std::array': too few template arguments    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 50  
Error   C2027   use of undefined type 'std::array'  CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 50  
Error   C2582   'operator =' function is unavailable in 'std::array'    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 52  
Error   C2582   'operator =' function is unavailable in 'std::array'    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 53  
Error   C2582   'operator =' function is unavailable in 'std::array'    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 54  
Error C2664 'void CalculatorLibrary::ExternalInterface::AddHubInformationv                    (int,cli::array<double,1> ^,cli::array<System::String ^,1> ^,cli::array<System::String ^,1> ^)': cannot  convert argument 2 from 'std::array *' to 'cli::array<double,1> ^'   CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 57  
Error   C2976   'std::array': too few template arguments    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 76  
Error   C3699   '^': cannot use this indirection on type 'std::array'   CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 76  
Error   C2976   'std::array': too few template arguments    CalculatorsAIMMSInterop C:DELTANDHCalculatorsDevelopmentCalculatorsAIMMSInteropCalculatorsAIMMSInterop.cpp 76  

Here is the code which is failing:

#include "stdafx.h"
#include <msclr/marshal.h>
#include "CalculatorsAIMMSInterop.h"

using namespace msclr::interop;
using namespace System;
using namespace System::Reflection;
using namespace std;

void marshalString(System::String^ input, char* output)
{
    //marshal_context ^ context = MarshalContextSingleton::GetInstance();
    marshal_context ^ context = gcnew marshal_context();
    const char* strResult = context->marshal_as<const char*>(input);
    strcpy(output, strResult);
    delete context;
}

void marshalInt(System::Int32 input, char* output) 
{
    //marshal_context ^ context = MarshalContextSingleton::GetInstance();
    marshal_context ^ context = gcnew marshal_context();
    const char* strResult = context->marshal_as<const char*> (""+input);
    strcpy(output, strResult);
    delete context;
}

System::String^ marshalString(char* input)
{
    //marshal_context ^ context = MarshalContextSingleton::GetInstance();
    marshal_context ^ context = gcnew marshal_context();
    System::String^ output = context->marshal_as<System::String^>(input);
    delete context;
    return output;
}

// Methods for hub activity calculator
void WINAPI HubActivityInitialize(int calenderStart, int calendarEnd) {
    CalculatorLibrary::ExternalInterface::InitializeHubActivityCalculator(calenderStart, calendarEnd);
}

void WINAPI HubActivityAddInformation(int numberOfValues, double* activities, char** arrivalTimes, char** departureTimes) {
    array<double>^ activitiesDoubles = gcnew array<double>(numberOfValues);
    array<String^>^ arrivalTimeStrs = gcnew array<String^>(numberOfValues);
    array<String^>^ departureTimeStrs = gcnew array<String^>(numberOfValues);

    array<int>^ arrivalTimeInts = gcnew array<int>(numberOfValues);
    array<int>^ departureTimeInts = gcnew array<int>(numberOfValues);
    for (int i = 0; i < numberOfValues; i++) {
        activitiesDoubles[i] = activities[i];
        arrivalTimeStrs[i] = marshalString(arrivalTimes[i]);
        departureTimeStrs[i] = marshalString(departureTimes[i]);
    }

    CalculatorLibrary::ExternalInterface::AddHubInformation(numberOfValues, activitiesDoubles, arrivalTimeStrs, departureTimeStrs);
}

void WINAPI HubActivityGet(double* amounts) {
    System::Collections::Generic::List<double>^ hubActivityAmounts = CalculatorLibrary::ExternalInterface::GetHubActivity();
    for(int i = 0; i < hubActivityAmounts->Count; i++ )
    {
        amounts[i] = hubActivityAmounts[i];
    }
}

void WINAPI HubActivityReset() {
    CalculatorLibrary::ExternalInterface::ResetHubActivity();
}

// Methods for conveying calculator
void WINAPI ConveyingInitialize(int start, int end, char** startedConveyingQuantity) {
    int numberOfValues = end - start + 1;

    array<String^>^ quantity = gcnew array<String^>(numberOfValues);
    for (int i = 0; i < numberOfValues; i++) {
        quantity[i] = marshalString(startedConveyingQuantity[i]);
    }

    CalculatorLibrary::ExternalInterface::InitializeConveyingCalculator(start, end, quantity);
}

void WINAPI ConveyingAddPieceInformation(int numberOfPieces, char** inMovementsIds) {
    array<String^>^ incomingMovementIds = gcnew array<String^>(numberOfPieces);

    for (int i = 0; i < numberOfPieces; i++) {
        incomingMovementIds[i] = marshalString(inMovementsIds[i]);
    }

    CalculatorLibrary::ExternalInterface::AddConveyingPieceInformation(numberOfPieces, incomingMovementIds);
}

void WINAPI ConveyingAddConnectionInformation(int numberOfConnections, char** inMovementsIds, char** outMovementsIds, char** numberOfConnectedPieces) {
    array<String^>^ incomingMovementIds = gcnew array<String^>(numberOfConnections);
    array<String^>^ outgoingMovementIds = gcnew array<String^>(numberOfConnections);
    array<String^>^ connectedPieces = gcnew array<String^>(numberOfConnections);

    for (int i = 0; i < numberOfConnections; i++) {
        incomingMovementIds[i] = marshalString(inMovementsIds[i]);
        outgoingMovementIds[i] = marshalString(outMovementsIds[i]);
        connectedPieces[i] = marshalString(numberOfConnectedPieces[i]);
    }

    CalculatorLibrary::ExternalInterface::AddConveyingConnectionInformation(incomingMovementIds, outgoingMovementIds, connectedPieces);
}

void WINAPI ConveyingRunCalculation() {
    CalculatorLibrary::ExternalInterface::RunConveyingCalculation();
}

void WINAPI ConveyingResultGet(char** pieceMovementIDOut, char** pieceTimeAtConveyor) {
    array<int>^ pieceOutgoingMovement = CalculatorLibrary::ExternalInterface::GetPieceOutgoingMovement();
    array<int>^ pieceConveyorEntryTime = CalculatorLibrary::ExternalInterface::GetPieceConveyorEntryTime();

    for(int i = 0; i < pieceOutgoingMovement->Length; i++ )
    {
        marshalInt(pieceOutgoingMovement[i], pieceMovementIDOut[i]);
        marshalInt(pieceConveyorEntryTime[i], pieceTimeAtConveyor[i]);
    }
}

void WINAPI ConveyingReset() {
    CalculatorLibrary::ExternalInterface::ResetConveying();
}

// Methods for conveying calculator via text files
void WINAPI ConveyingInitializeFromFile(char* filePath) {
    String^ path = marshalString(filePath);
    CalculatorLibrary::ExternalInterface::InitializeConveyingCalculator(path);
}

void WINAPI WriteConveyingCalculationToFile(char* filePath) {
    String^ path = marshalString(filePath);
    CalculatorLibrary::ExternalInterface::WriteConveyingCalculatorData(path);
}

// Methods for Route Generation
void WINAPI InitializeCaseWithLogging(char* logfile_name) {
    RouteGeneration::IO::ExternalInterface::Initialize(marshalString(logfile_name));
}

int WINAPI GetRouteGenerationInputErrorCount() {
    return RouteGeneration::IO::ExternalInterface::CloseErrorLogAndRetrieveErrorCount();
}

void WINAPI RouteGenerationInitializeFromFiles(char* filePath1, char* filePath2, char* errorMessage) {
    String^ path1 = marshalString(filePath1);
    String^ message1 = RouteGeneration::IO::ExternalInterface::ReadNetworkModelInformation(path1);

    if (message1 != "OK") {
        marshalString(message1, errorMessage);
        return;
    }

    String^ path2 = marshalString(filePath2);
    String^ message2 = RouteGeneration::IO::ExternalInterface::ReadRouteGenerationRequests(path2);

    marshalString(message2, errorMessage);
}

void WINAPI RunRouteGeneration() {
    RouteGeneration::IO::ExternalInterface::GenerateRoutes();
}

void WINAPI RunAllToAllRouteGeneration(char* modelDataFilePath, char* requestDataFilePath, char* databaseFilePath, char* errorMessage) {
    String^ modelDataPath = marshalString(modelDataFilePath);
    String^ requestDataPath = marshalString(requestDataFilePath);
    String^ databasePath = marshalString(databaseFilePath);

    String^ message = RouteGeneration::IO::ExternalInterface::ReadAndGenerateAllToAllRoutes(modelDataPath, requestDataPath, databasePath);
    marshalString(message, errorMessage);
}

void WINAPI WriteGeneratedRoutesToFile(char* filePath, char* errorMessage) {
    String^ path = marshalString(filePath);
    String^ message = RouteGeneration::IO::ExternalInterface::WriteGeneratedRoutes(path);

    marshalString(message, errorMessage);
}

void WINAPI RouteGenerationReset() {
    RouteGeneration::IO::ExternalInterface::CleanMemory();
}

// Methods for Hub Simulation
void WINAPI InitializeSimulationCaseWithLogging(char* logfile_name) {
    HubSimulation::IO::ExternalInterface::Initialize(marshalString(logfile_name));
}

int WINAPI GetHubSimulationInputErrorCount() {
    return HubSimulation::IO::ExternalInterface::CloseErrorLogAndRetrieveErrorCount();
}

void WINAPI HubSimulationInitializeFromFiles(char* filePath1, char* filePath2, char* errorMessage) {
    String^ path1 = marshalString(filePath1);
    String^ message1 = HubSimulation::IO::ExternalInterface::ReadHubSimulationModelInformation(path1);

    if (message1 != "OK") {
        marshalString(message1, errorMessage);
        return;
    }

    String^ path2 = marshalString(filePath2);
    String^ message2 = HubSimulation::IO::ExternalInterface::ReadPiecesInformation(path2);

    marshalString(message2, errorMessage);
}

void WINAPI RunHubSimulation() {
    HubSimulation::IO::ExternalInterface::RunSimulation();
}

void WINAPI WriteHubSimulationResultsToFile(char* filePath, char* errorMessage) {
    String^ path = marshalString(filePath);

    String^ message = HubSimulation::IO::ExternalInterface::WriteSimulationResults(path);
    marshalString(message, errorMessage);
}

void WINAPI HubSimulationReset() {
    HubSimulation::IO::ExternalInterface::CleanMemory();
}

I’ve made this «Socialite» class, and a separate «Faction» class. One of the arguments for the Socialite object is a vector of pointers to «Factions». I had used the Socialite class earlier without the ‘factionlist’ as a parameter, and it worked fine.

class Socialite
{
public:

 Socialite();
 Socialite(string lastName, string firstName, string userId, string picture, string website, string description, list<Faction*> factionlist);

 //other methods

 void newSocialite(string lastName, string firstName, string userId, string picture, string website, string description, list<Faction*> factionlist);
 void deleteSocialite(string lastName, string firstName, string userId, string picture, string website, string description, list<Faction*> factionlist);

 //other methods

private:

 string lastName_;
 string firstName_;
 string userId_;
 string picture_;
 string website_;
 string description_;

 vector<Socialite *> socialiteptr_;
 list<Faction*> factionlist_;



};

When I included it however, I get the errors:

 error C2976: 'std::list' : too few template arguments  

and

 error C2065: 'Faction' : undeclared identifier 

on the same line every time my method/constructor contains a factionlist. The solutions I looked up involved code using templates, and I’m not using any, so I don’t understand what’s wrong.

Extra info: My vector of pointers is stored in such a way:

 vector<Faction *> factionptr_;

And I make it into a list in such a way:

 list<Faction*> list_factions(factionptr_.begin(), factionptr_.end());

What am I doing wrong?

I’ve made this «Socialite» class, and a separate «Faction» class. One of the arguments for the Socialite object is a vector of pointers to «Factions». I had used the Socialite class earlier without the ‘factionlist’ as a parameter, and it worked fine.

class Socialite
{
public:

 Socialite();
 Socialite(string lastName, string firstName, string userId, string picture, string website, string description, list<Faction*> factionlist);

 //other methods

 void newSocialite(string lastName, string firstName, string userId, string picture, string website, string description, list<Faction*> factionlist);
 void deleteSocialite(string lastName, string firstName, string userId, string picture, string website, string description, list<Faction*> factionlist);

 //other methods

private:

 string lastName_;
 string firstName_;
 string userId_;
 string picture_;
 string website_;
 string description_;

 vector<Socialite *> socialiteptr_;
 list<Faction*> factionlist_;



};

When I included it however, I get the errors:

 error C2976: 'std::list' : too few template arguments  

and

 error C2065: 'Faction' : undeclared identifier 

on the same line every time my method/constructor contains a factionlist. The solutions I looked up involved code using templates, and I’m not using any, so I don’t understand what’s wrong.

Extra info: My vector of pointers is stored in such a way:

 vector<Faction *> factionptr_;

And I make it into a list in such a way:

 list<Faction*> list_factions(factionptr_.begin(), factionptr_.end());

What am I doing wrong?

cjv

0 / 0 / 1

Регистрация: 20.07.2017

Сообщений: 15

1

09.08.2018, 10:34. Показов 2970. Ответов 7

Метки нет (Все метки)


У меня есть форма MainForm и библиотека cyplib.h внутри одного проекта. Я хочу использовать функции из библиотеки при работе с моей формой. Для этого я пытаюсь включить библиотеку в MainForm.h или в MainForm.cpp. Но как только я куда-то её включаю, сразу же появляются ошибки в MainForm.cpp

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "MainForm.h"
#include "cyplib.h"
 
using namespace System;
using namespace System::Windows::Forms;
 
[STAThreadAttribute]
int main(array < String^> ^ args) {
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);
    Cipher::MainForm form;
    Application::Run(%form);
    return 0;
}

Ошибка C2976 std::array: слишком мало аргументов шаблон Cipher c:usersusersourcereposcipherciphermainform. cpp 8

Ошибка C3699 ^: это косвенное обращение невозможно использовать для типа «std::array» Cipher c:usersusersourcereposcipherciphermainform. cpp 8

Что с этим делать?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



OwenGlendower

Администратор

Эксперт .NET

15248 / 12287 / 4904

Регистрация: 17.03.2014

Сообщений: 24,884

Записей в блоге: 1

09.08.2018, 11:49

2

Лучший ответ Сообщение было отмечено cjv как решение

Решение

cjv,

C++
9
int main(cli::array < String^> ^ args) {



1



0 / 0 / 1

Регистрация: 20.07.2017

Сообщений: 15

09.08.2018, 12:06

 [ТС]

3

Теперь всё выглядит ещё страшнее (6 предупреждений были и раньше)

Ошибки C2976 и C3699



0



Администратор

Эксперт .NET

15248 / 12287 / 4904

Регистрация: 17.03.2014

Сообщений: 24,884

Записей в блоге: 1

09.08.2018, 12:16

4

cjv, «переведи» эти сообщения с помощью декодера и действуй с в соответствии с текстом ошибок.



0



0 / 0 / 1

Регистрация: 20.07.2017

Сообщений: 15

09.08.2018, 13:15

 [ТС]

5

OwenGlendower, в общем, ему не нравились моя локализация. В одном месте я вместо L» привет « выводил в поток wcout просто » привет «.
А за cli::array огромное спасибо! Странно, что ни в одной инструкции по работе с формами, которую я видел, не сказано про это.



0



Администратор

Эксперт .NET

15248 / 12287 / 4904

Регистрация: 17.03.2014

Сообщений: 24,884

Записей в блоге: 1

09.08.2018, 13:35

6

cjv, в инструкциях об этом не пишут потому что это не имеет к отношения к формам. Это базовые правила языка которые программист уже должен знать.



0



cjv

0 / 0 / 1

Регистрация: 20.07.2017

Сообщений: 15

09.08.2018, 14:49

 [ТС]

7

Теперь у меня другая проблема. Когда я добавляю

C++
1
#include "msclrmarshal_cppstd.h"

в mainform.h или в mainform.cpp, чтобы преобразовывать System::String^ в std::wstring, возникают 11 ошибок в кодировке IBM866. Вот они в нормальной кодировке:
1>MSVCMRTD.lib(mstartup.obj) : error LNK2022: сбой операции с метаданными (80131195): Несовместимые особые атрибуты. (0x0c0001fe).
1>MSVCMRTD.lib(mstartup.obj) : error LNK2022: сбой операции с метаданными (80131195): Несовместимые особые атрибуты. (0x0c000201).
1>MSVCMRTD.lib(managdeh.obj) : error LNK2022: сбой операции с метаданными (80131195): Несовместимые особые атрибуты. (0x0c0000dd).
1>MSVCMRTD.lib(managdeh.obj) : error LNK2022: сбой операции с метаданными (80131195): Несовместимые особые атрибуты. (0x0c0000de).
1>MSVCMRTD.lib(mehvecdtr.obj) : error LNK2022: сбой операции с метаданными (80131195): Несовместимые особые атрибуты. (0x0c0000b4).
1>MSVCMRTD.lib(mehvecdtr.obj) : error LNK2022: сбой операции с метаданными (80131195): Несовместимые особые атрибуты. (0x0c0000b7).
1>MSVCMRTD.lib(msilexit.obj) : error LNK2022: сбой операции с метаданными (80131195): Несовместимые особые атрибуты. (0x0c000106).
1>MSVCMRTD.lib(msilexit.obj) : error LNK2022: сбой операции с метаданными (80131195): Несовместимые особые атрибуты. (0x0c000109).
1>MSVCMRTD.lib(pureMSILcode.obj) : error LNK2022: сбой операции с метаданными (80131195): Несовместимые особые атрибуты. (0x0c0001b9).
1>MSVCMRTD.lib(pureMSILcode.obj) : error LNK2022: сбой операции с метаданными (80131195): Несовместимые особые атрибуты. (0x0c0001bb).
1>LINK : fatal error LNK1255: не удалось выполнить компоновку из-за ошибок в метаданных

Хотя бы на этот раз ошибка не в моей библиотеке.



0



0 / 0 / 1

Регистрация: 20.07.2017

Сообщений: 15

11.08.2018, 11:05

 [ТС]

8

Оказалось, что маршалинг не поддерживается в версии .NET Framework 3.5. Грустно. Придётся искать более извращённые способы преобразования типов.



0



Я работаю над проектом форм Windows в C ++ Express 2010. Внесены некоторые изменения в Form.h и теперь получаю ошибку при компиляции программы. Обратите внимание, что компилятор предполагает, что ошибка в основной программе — open gl test 2 — тот #includes форма. Все скомпилировалось отлично в течение нескольких дней, пока я разрабатывал код, затем что-то изменил вчера вечером, и теперь я получаю сообщение об ошибке.

Основная программа в тесте open gl 2 идентична той из любого другого проекта, основанного на формах, который я создал — я сравнил с проверкой [за исключением очевидных изменений пространства имен и т. Д., Вызывающих другой проект]

// open gl test 2.cpp : main project file.

#include "stdafx.h"#include "Form1.h"
using namespace opengltest2;

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);

// Create the main window and run it
Application::Run(gcnew Form1());
return 0;
}

Ошибка:

1>open gl test 2.cpp(9): error C2976: 'std::tr1::array' : too few template arguments
1>          D:Program Files (x86)Microsoft Visual Studio 10.0VCincludearray(18) : see declaration of 'std::tr1::array'
1>open gl test 2.cpp(9): error C3699: '^' : cannot use this indirection on type 'std::tr1::array'
1>          compiler replacing '^' with '*' to continue parsing

строка, на которую жалуется компилятор

int main(array<System::String ^> ^args)

Таким образом, ошибка не может быть в том, что, как утверждает компилятор, — и я не могу найти ошибку в коде во включенных файлах — они компилируются правильно. Я предполагаю, что ошибка ДОЛЖНА быть в form.h, потому что это то, что я изменил, что вызывает эту ошибку, но я не могу ее увидеть. И я почти уверен, что не изменил некоторые настройки проекта.

Я не включаю код для form1.h, потому что это слишком долго. Угадайте, что я ищу, так это опыт людей по поиску ошибки. Какие стратегии я могу использовать, чтобы решить эту проблему? Если бы у меня были волосы, чтобы выдернуть их, я был бы окружен ими. Пожалуйста, помогите мне спасти мои несуществующие волосы.

-1

Решение

Похоже, что компилятор запутался между типом управляемого массива и типом массива в библиотеке std. Это, вероятно, потому что где-то вы делаете using namespace std — в идеале вы должны явно ссылаться на правильное пространство имен (std :: array или cli :: array) или удалить включение <array> если это не нужно

Обратите внимание, что постоянный размер std :: array не подходит для использования с аргументами командной строки — вам все равно придется использовать контейнер переменного размера, такой как cli :: array.

13

Другие решения

I am trying to create a vector of custom objects defined in a header file and then initialize them in the actual cpp file. I’m getting the following errors in Visual Studio:

error C2976: 'std::vector' : too few template arguments
error C2065: 'Particle' : undeclared identifier
error C2059: syntax error : '>'

In the code below, the vector is defined in Explosion.h.

Particle.h:

#pragma once
class Particle : public sf::CircleShape {
public:
    float speed;
    bool alive;
    float vx;
    float vy;
    Particle(float x, float y, float vx, float vy, sf::Color color);
    ~Particle();
};

Particle.cpp:

#include <SFML/Graphics.hpp>
#include "Particle.h"

Particle::Particle(float x, float y, float vx, float vy, sf::Color color) {
    // Inherited
    this->setPosition(x, y);
    this->setRadius(5);
    this->setFillColor(color);

    // Player Defined Variables
    this->speed = (float).05;
    this->alive = true;
    this->vx = vx;
    this->vy = vy;
}

Particle::~Particle() {
}

Explosion.h:

static const int NUM_PARTICLES = 6;

#pragma once
class Explosion {
public:
    std::vector<Particle*> particles;
    bool alive;
    Explosion();
    ~Explosion();
};

Explosion.cpp:

#include <SFML/Graphics.hpp>
#include "Particle.h"
#include "Explosion.h"

Explosion::Explosion() {
    this->alive = true;

    // Add Particles to vector
    for (int i = 0; i < NUM_PARTICLES; i++) {
        this->particles.push_back(new Particle(0, 0, 0, 0, sf::Color::Red));
    }
}

Explosion::~Explosion() {
}

I’m sure there is something fundamentally wrong here since C++ is fairly new to me.

I am trying to create a vector of custom objects defined in a header file and then initialize them in the actual cpp file. I’m getting the following errors in Visual Studio:

error C2976: 'std::vector' : too few template arguments
error C2065: 'Particle' : undeclared identifier
error C2059: syntax error : '>'

In the code below, the vector is defined in Explosion.h.

Particle.h:

#pragma once
class Particle : public sf::CircleShape {
public:
    float speed;
    bool alive;
    float vx;
    float vy;
    Particle(float x, float y, float vx, float vy, sf::Color color);
    ~Particle();
};

Particle.cpp:

#include <SFML/Graphics.hpp>
#include "Particle.h"

Particle::Particle(float x, float y, float vx, float vy, sf::Color color) {
    // Inherited
    this->setPosition(x, y);
    this->setRadius(5);
    this->setFillColor(color);

    // Player Defined Variables
    this->speed = (float).05;
    this->alive = true;
    this->vx = vx;
    this->vy = vy;
}

Particle::~Particle() {
}

Explosion.h:

static const int NUM_PARTICLES = 6;

#pragma once
class Explosion {
public:
    std::vector<Particle*> particles;
    bool alive;
    Explosion();
    ~Explosion();
};

Explosion.cpp:

#include <SFML/Graphics.hpp>
#include "Particle.h"
#include "Explosion.h"

Explosion::Explosion() {
    this->alive = true;

    // Add Particles to vector
    for (int i = 0; i < NUM_PARTICLES; i++) {
        this->particles.push_back(new Particle(0, 0, 0, 0, sf::Color::Red));
    }
}

Explosion::~Explosion() {
}

I’m sure there is something fundamentally wrong here since C++ is fairly new to me.

Понравилась статья? Поделить с друзьями:
  • Error c2784 c
  • Error c2760 синтаксическая ошибка непредвиденный токен идентификатор требуется спецификатор типа
  • Error c2731 winmain функция не может быть перегружена
  • Error c2712 cannot use try in functions that require object unwinding
  • Error c2679 бинарный не найден оператор принимающий правый операнд типа