У меня есть некоторые проблемы с моим кодом C ++. Я пытаюсь теперь разделить заголовочный файл, который содержит определения и объявления некоторых указателей на символы (ранее строки, но у меня были некоторые проблемы с CRT, поэтому я изменил их на указатель на символ). Так как я изменил их на указатель на символ, я получаю ошибки переопределения.
test.h
#pragma once
#define DllExport __declspec( dllexport )
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <stdexcept>
#include "TestConstantsHeader.cpp"
namespace DataVerifier
{
class DllExport CDataVerifier
{
public:
CDataVerifier();
~CDataVerifier();
//! @brief A function that processes the messages
void Process();
};
}
test.cpp
#include "Test.h"
using namespace DataVerifier;
CDataVerifier::CDataVerifier()
{
}
CDataVerifier::~CDataVerifier(){}
void CDataVerifier::Process()
{
const char* strTmp = Structure::strHTMLTemplate;
strTmp = "hello";
std::cout << strTmp;
}
TestConstantsHeader.h
#pragma once
#define DllExport __declspec( dllexport )
#include <iostream>
namespace DataVerifier
{
namespace Structure
{
const char *strHTMLTemplate;/* = "<doctype html>""<html lang=\"en\">""<head>""<meta charset=\"utf-8\"/>""<title>Data Verifier Test Results - {@testdesc}</title>""<style>""body {""\tbackground: none repeat scroll 0 0 #F3F3F4;""\tcolor: #1E1E1F;""\tfont-family: \"Segoe UI\",Tahoma,Geneva,Verdana,sans-serif;""\tmargin: 0;""\tpadding: 0;""}""h1 {""\tbackground-color: #E2E2E2;""\tborder-bottom: 1px solid #C1C1C2;""\tcolor: #201F20;""\tfont-size: 21pt;""\tfont-weight: normal;""\tmargin: 0;""\tpadding: 10px 0 10px 10px;""}""h2 {""\tfont-size: 18pt;""\tfont-weight: normal;""\tmargin: 0;""\tpadding: 15px 0 5px;""}""h3 {""\tbackground-color: rgba(0, 0, 0, 0);""\tfont-size: 15pt;""\tfont-weight: normal;""\tmargin: 0;""\tpadding: 15px 0 5px;""}""a {""\tcolor: #1382CE;""}""table {""\tborder-collapse: collapse;""\tborder-spacing: 0;""\tfont-size: 10pt;""}""table th {""\tbackground: none repeat scroll 0 0 #E7E7E8;""\tfont-weight: normal;""\tpadding: 3px 6px;""\ttext-align: left;""\ttext-decoration: none;""}""table td {""\tbackground: none repeat scroll 0 0 #F7F7F8;""\tborder: 1px solid #E7E7E8;""\tmargin: 0;""\tpadding: 3px 6px 5px 5px;""\tvertical-align: top;""}"""".textCentered {""\ttext-align: center;""}"".messageCell {""\twidth: 100;""}""#content {""\tpadding: 0 12px 12px;""}""#overview table {""\tmax-width: 75;""\twidth: auto;""}""#messages table {""\twidth: 97;""}""</style>""</head>""<body>""<div id=\"big_wrapper\">""\t<h1>Test Results - {@testdesc}</h1>""\t<table>""{@eeddata}""\t</table>""</body>""</html>";*/
}
}
TestConstantsHeader.cpp
#include "TestConstantsHeader.h"
namespace DataVerifier
{
namespace Structure
{
const char *strHTMLTemplate = "<doctype html>""<html lang=\"en\">""<head>""<meta charset=\"utf-8\"/>""<title>Data Verifier Test Results - {@testdesc}</title>""<style>""body {""\tbackground: none repeat scroll 0 0 #F3F3F4;""\tcolor: #1E1E1F;""\tfont-family: \"Segoe UI\",Tahoma,Geneva,Verdana,sans-serif;""\tmargin: 0;""\tpadding: 0;""}""h1 {""\tbackground-color: #E2E2E2;""\tborder-bottom: 1px solid #C1C1C2;""\tcolor: #201F20;""\tfont-size: 21pt;""\tfont-weight: normal;""\tmargin: 0;""\tpadding: 10px 0 10px 10px;""}""h2 {""\tfont-size: 18pt;""\tfont-weight: normal;""\tmargin: 0;""\tpadding: 15px 0 5px;""}""h3 {""\tbackground-color: rgba(0, 0, 0, 0);""\tfont-size: 15pt;""\tfont-weight: normal;""\tmargin: 0;""\tpadding: 15px 0 5px;""}""a {""\tcolor: #1382CE;""}""table {""\tborder-collapse: collapse;""\tborder-spacing: 0;""\tfont-size: 10pt;""}""table th {""\tbackground: none repeat scroll 0 0 #E7E7E8;""\tfont-weight: normal;""\tpadding: 3px 6px;""\ttext-align: left;""\ttext-decoration: none;""}""table td {""\tbackground: none repeat scroll 0 0 #F7F7F8;""\tborder: 1px solid #E7E7E8;""\tmargin: 0;""\tpadding: 3px 6px 5px 5px;""\tvertical-align: top;""}"""".textCentered {""\ttext-align: center;""}"".messageCell {""\twidth: 100;""}""#content {""\tpadding: 0 12px 12px;""}""#overview table {""\tmax-width: 75;""\twidth: auto;""}""#messages table {""\twidth: 97;""}""</style>""</head>""<body>""<div id=\"big_wrapper\">""\t<h1>Test Results - {@testdesc}</h1>""\t<table>""{@eeddata}""\t</table>""</body>""</html>";
};
};
На самом деле не знаю, что я делаю здесь не так …
Это ошибка, которую я получаю:
Ошибка 2 ошибка C2086: ‘const char * DataVerifier :: Structure :: strHTMLTemplate’: переопределение c: \ users \ suzan \ documents \ visual studio 2013 \ projects \ test1 \ test1 \ testconstantsheader.cpp 7 1 Test1
Ошибка 3 ошибка C2086: ‘const char * DataVerifier :: Structure :: strHTMLTemplate’: переопределение c: \ users \ suzan \ documents \ visual studio 2013 \ projects \ test1 \ test1 \ testconstantsheader.cpp 7 1 Test1
0
Решение
Ваш заголовочный файл содержит определение объекта strHTMLTemplate
с внешней связью. Это то, что приводит к множественной ошибке определения.
Изменить определение strHTMLTemplate
в заголовочном файле в не определяющая декларация добавив ключевое слово extern
// TestConstantsHeader.h
namespace DataVerifier
{
namespace Structure
{
extern const char *strHTMLTemplate;
}
}
Кроме того, вероятно, имеет смысл объявить указатель как const char *const strHTMLTemplate
, Это не похоже, что это должно быть изменяемым.
3
Другие решения
I’m having some issues with my C++ code. I’m trying to now split a header file which has definitions and declarations of some char pointers (previously strings but i’ve been having some CRT issues so changing them to a char pointer). Since I’ve changed them to a char pointer, i’m getting redefinition errors.
Test.h
#pragma once
#define DllExport __declspec( dllexport )
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <stdexcept>
#include "TestConstantsHeader.cpp"
namespace DataVerifier
{
class DllExport CDataVerifier
{
public:
CDataVerifier();
~CDataVerifier();
//! @brief A function that processes the messages
void Process();
};
}
Test.cpp
#include "Test.h"
using namespace DataVerifier;
CDataVerifier::CDataVerifier()
{
}
CDataVerifier::~CDataVerifier(){}
void CDataVerifier::Process()
{
const char* strTmp = Structure::strHTMLTemplate;
strTmp = "hello";
std::cout << strTmp;
}
TestConstantsHeader.h
#pragma once
#define DllExport __declspec( dllexport )
#include <iostream>
namespace DataVerifier
{
namespace Structure
{
const char *strHTMLTemplate;/* = "<doctype html>"
"<html lang=\"en\">"
"<head>"
"<meta charset=\"utf-8\"/>"
"<title>Data Verifier Test Results - {@testdesc}</title>"
"<style>"
"body {"
"\tbackground: none repeat scroll 0 0 #F3F3F4;"
"\tcolor: #1E1E1F;"
"\tfont-family: \"Segoe UI\",Tahoma,Geneva,Verdana,sans-serif;"
"\tmargin: 0;"
"\tpadding: 0;"
"}"
"h1 {"
"\tbackground-color: #E2E2E2;"
"\tborder-bottom: 1px solid #C1C1C2;"
"\tcolor: #201F20;"
"\tfont-size: 21pt;"
"\tfont-weight: normal;"
"\tmargin: 0;"
"\tpadding: 10px 0 10px 10px;"
"}"
"h2 {"
"\tfont-size: 18pt;"
"\tfont-weight: normal;"
"\tmargin: 0;"
"\tpadding: 15px 0 5px;"
"}"
"h3 {"
"\tbackground-color: rgba(0, 0, 0, 0);"
"\tfont-size: 15pt;"
"\tfont-weight: normal;"
"\tmargin: 0;"
"\tpadding: 15px 0 5px;"
"}"
"a {"
"\tcolor: #1382CE;"
"}"
"table {"
"\tborder-collapse: collapse;"
"\tborder-spacing: 0;"
"\tfont-size: 10pt;"
"}"
"table th {"
"\tbackground: none repeat scroll 0 0 #E7E7E8;"
"\tfont-weight: normal;"
"\tpadding: 3px 6px;"
"\ttext-align: left;"
"\ttext-decoration: none;"
"}"
"table td {"
"\tbackground: none repeat scroll 0 0 #F7F7F8;"
"\tborder: 1px solid #E7E7E8;"
"\tmargin: 0;"
"\tpadding: 3px 6px 5px 5px;"
"\tvertical-align: top;"
"}"
""
".textCentered {"
"\ttext-align: center;"
"}"
".messageCell {"
"\twidth: 100;"
"}"
"#content {"
"\tpadding: 0 12px 12px;"
"}"
"#overview table {"
"\tmax-width: 75;"
"\twidth: auto;"
"}"
"#messages table {"
"\twidth: 97;"
"}"
"</style>"
"</head>"
"<body>"
"<div id=\"big_wrapper\">"
"\t<h1>Test Results - {@testdesc}</h1>"
"\t<table>"
"{@eeddata}"
"\t</table>"
"</body>"
"</html>";*/
}
}
TestConstantsHeader.cpp
#include "TestConstantsHeader.h"
namespace DataVerifier
{
namespace Structure
{
const char *strHTMLTemplate = "<doctype html>"
"<html lang=\"en\">"
"<head>"
"<meta charset=\"utf-8\"/>"
"<title>Data Verifier Test Results - {@testdesc}</title>"
"<style>"
"body {"
"\tbackground: none repeat scroll 0 0 #F3F3F4;"
"\tcolor: #1E1E1F;"
"\tfont-family: \"Segoe UI\",Tahoma,Geneva,Verdana,sans-serif;"
"\tmargin: 0;"
"\tpadding: 0;"
"}"
"h1 {"
"\tbackground-color: #E2E2E2;"
"\tborder-bottom: 1px solid #C1C1C2;"
"\tcolor: #201F20;"
"\tfont-size: 21pt;"
"\tfont-weight: normal;"
"\tmargin: 0;"
"\tpadding: 10px 0 10px 10px;"
"}"
"h2 {"
"\tfont-size: 18pt;"
"\tfont-weight: normal;"
"\tmargin: 0;"
"\tpadding: 15px 0 5px;"
"}"
"h3 {"
"\tbackground-color: rgba(0, 0, 0, 0);"
"\tfont-size: 15pt;"
"\tfont-weight: normal;"
"\tmargin: 0;"
"\tpadding: 15px 0 5px;"
"}"
"a {"
"\tcolor: #1382CE;"
"}"
"table {"
"\tborder-collapse: collapse;"
"\tborder-spacing: 0;"
"\tfont-size: 10pt;"
"}"
"table th {"
"\tbackground: none repeat scroll 0 0 #E7E7E8;"
"\tfont-weight: normal;"
"\tpadding: 3px 6px;"
"\ttext-align: left;"
"\ttext-decoration: none;"
"}"
"table td {"
"\tbackground: none repeat scroll 0 0 #F7F7F8;"
"\tborder: 1px solid #E7E7E8;"
"\tmargin: 0;"
"\tpadding: 3px 6px 5px 5px;"
"\tvertical-align: top;"
"}"
""
".textCentered {"
"\ttext-align: center;"
"}"
".messageCell {"
"\twidth: 100;"
"}"
"#content {"
"\tpadding: 0 12px 12px;"
"}"
"#overview table {"
"\tmax-width: 75;"
"\twidth: auto;"
"}"
"#messages table {"
"\twidth: 97;"
"}"
"</style>"
"</head>"
"<body>"
"<div id=\"big_wrapper\">"
"\t<h1>Test Results - {@testdesc}</h1>"
"\t<table>"
"{@eeddata}"
"\t</table>"
"</body>"
"</html>";
};
};
Really don’t know what I’m doing wrong here…
This is the error i’m getting:
Error 2 error C2086: ‘const char *DataVerifier::Structure::strHTMLTemplate’ : redefinition c:\users\suzan\documents\visual studio 2013\projects\test1\test1\testconstantsheader.cpp 7 1 Test1
Error 3 error C2086: ‘const char *DataVerifier::Structure::strHTMLTemplate’ : redefinition c:\users\suzan\documents\visual studio 2013\projects\test1\test1\testconstantsheader.cpp 7 1 Test1
Перейти к контенту
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2086 |
Compiler Error C2086 |
11/04/2016 |
C2086 |
C2086 |
4329bf72-90c8-444c-8524-4ef75e6b2139 |
Compiler Error C2086
‘identifier’ : redefinition
The identifier is defined more than once, or a subsequent declaration differs from a previous one.
C2086 can also be the result of incremental building for a referenced C# assembly. Rebuild the C# assembly to resolve this error.
The following sample generates C2086:
// C2086.cpp main() { int a; int a; // C2086 not an error in ANSI C }
vip72 11 / 11 / 7 Регистрация: 18.01.2014 Сообщений: 180 Записей в блоге: 1 |
||||
1 |
||||
21.08.2014, 02:11. Показов 5480. Ответов 3 Метки нет (Все метки)
Хочу программу заделать чтобы нагрузить немного свой сайт (в коде на примере гугла)
То есть я одновременно пытаюсь запустить проверку пинга у гугла 3 раза, обычно это делают запустив 3 раза отдельно командную строку и запуская проверку, а я хочу одновременно в одной Лог: 1>—— Построение начато: проект: lol2, Конфигурация: Debug Win32 —— 0 |
John Prick 2102 / 1622 / 691 Регистрация: 27.07.2012 Сообщений: 4,859 |
||||
21.08.2014, 02:22 |
2 |
|||
Три раза объявляешь один и тот же массив. Либо сделай разные массивы (cmd1, cmd2 …), либо убери эти повторные объявления. 1 |
vip72 11 / 11 / 7 Регистрация: 18.01.2014 Сообщений: 180 Записей в блоге: 1 |
||||||||
21.08.2014, 03:06 [ТС] |
3 |
|||||||
Как-то так чтоли:
Всё равно те же ошибки, напишите пожалуйста рабочий код, я просто новичек Добавлено через 35 минут
Первый пропингует а потом 2 ошибк подряд что слишком длинная входная строка, а надо одновременно пинговать 0 |
КОП 1123 / 794 / 219 Регистрация: 15.08.2010 Сообщений: 2,183 |
||||||||
21.08.2014, 06:33 |
4 |
|||||||
sprintf_s (cmd,»ping google.com -n 6″); для начала неплохо бы исправить cmd на cmd1 и cmd2 соответственно Добавлено через 1 час 13 минут так пойдет?
Добавлено через 1 час 43 минуты
1 |
У меня есть некоторые проблемы с моим кодом C ++. Я пытаюсь теперь разделить заголовочный файл, который содержит определения и объявления некоторых указателей на символы (ранее строки, но у меня были некоторые проблемы с CRT, поэтому я изменил их на указатель на символ). Так как я изменил их на указатель на символ, я получаю ошибки переопределения.
test.h
#pragma once
#define DllExport __declspec( dllexport )
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <stdexcept>
#include "TestConstantsHeader.cpp"
namespace DataVerifier
{
class DllExport CDataVerifier
{
public:
CDataVerifier();
~CDataVerifier();
//! @brief A function that processes the messages
void Process();
};
}
test.cpp
#include "Test.h"
using namespace DataVerifier;
CDataVerifier::CDataVerifier()
{
}
CDataVerifier::~CDataVerifier(){}
void CDataVerifier::Process()
{
const char* strTmp = Structure::strHTMLTemplate;
strTmp = "hello";
std::cout << strTmp;
}
TestConstantsHeader.h
#pragma once
#define DllExport __declspec( dllexport )
#include <iostream>
namespace DataVerifier
{
namespace Structure
{
const char *strHTMLTemplate;/* = "<doctype html>""<html lang="en">""<head>""<meta charset="utf-8"/>""<title>Data Verifier Test Results - {@testdesc}</title>""<style>""body {""tbackground: none repeat scroll 0 0 #F3F3F4;""tcolor: #1E1E1F;""tfont-family: "Segoe UI",Tahoma,Geneva,Verdana,sans-serif;""tmargin: 0;""tpadding: 0;""}""h1 {""tbackground-color: #E2E2E2;""tborder-bottom: 1px solid #C1C1C2;""tcolor: #201F20;""tfont-size: 21pt;""tfont-weight: normal;""tmargin: 0;""tpadding: 10px 0 10px 10px;""}""h2 {""tfont-size: 18pt;""tfont-weight: normal;""tmargin: 0;""tpadding: 15px 0 5px;""}""h3 {""tbackground-color: rgba(0, 0, 0, 0);""tfont-size: 15pt;""tfont-weight: normal;""tmargin: 0;""tpadding: 15px 0 5px;""}""a {""tcolor: #1382CE;""}""table {""tborder-collapse: collapse;""tborder-spacing: 0;""tfont-size: 10pt;""}""table th {""tbackground: none repeat scroll 0 0 #E7E7E8;""tfont-weight: normal;""tpadding: 3px 6px;""ttext-align: left;""ttext-decoration: none;""}""table td {""tbackground: none repeat scroll 0 0 #F7F7F8;""tborder: 1px solid #E7E7E8;""tmargin: 0;""tpadding: 3px 6px 5px 5px;""tvertical-align: top;""}"""".textCentered {""ttext-align: center;""}"".messageCell {""twidth: 100;""}""#content {""tpadding: 0 12px 12px;""}""#overview table {""tmax-width: 75;""twidth: auto;""}""#messages table {""twidth: 97;""}""</style>""</head>""<body>""<div id="big_wrapper">""t<h1>Test Results - {@testdesc}</h1>""t<table>""{@eeddata}""t</table>""</body>""</html>";*/
}
}
TestConstantsHeader.cpp
#include "TestConstantsHeader.h"
namespace DataVerifier
{
namespace Structure
{
const char *strHTMLTemplate = "<doctype html>""<html lang="en">""<head>""<meta charset="utf-8"/>""<title>Data Verifier Test Results - {@testdesc}</title>""<style>""body {""tbackground: none repeat scroll 0 0 #F3F3F4;""tcolor: #1E1E1F;""tfont-family: "Segoe UI",Tahoma,Geneva,Verdana,sans-serif;""tmargin: 0;""tpadding: 0;""}""h1 {""tbackground-color: #E2E2E2;""tborder-bottom: 1px solid #C1C1C2;""tcolor: #201F20;""tfont-size: 21pt;""tfont-weight: normal;""tmargin: 0;""tpadding: 10px 0 10px 10px;""}""h2 {""tfont-size: 18pt;""tfont-weight: normal;""tmargin: 0;""tpadding: 15px 0 5px;""}""h3 {""tbackground-color: rgba(0, 0, 0, 0);""tfont-size: 15pt;""tfont-weight: normal;""tmargin: 0;""tpadding: 15px 0 5px;""}""a {""tcolor: #1382CE;""}""table {""tborder-collapse: collapse;""tborder-spacing: 0;""tfont-size: 10pt;""}""table th {""tbackground: none repeat scroll 0 0 #E7E7E8;""tfont-weight: normal;""tpadding: 3px 6px;""ttext-align: left;""ttext-decoration: none;""}""table td {""tbackground: none repeat scroll 0 0 #F7F7F8;""tborder: 1px solid #E7E7E8;""tmargin: 0;""tpadding: 3px 6px 5px 5px;""tvertical-align: top;""}"""".textCentered {""ttext-align: center;""}"".messageCell {""twidth: 100;""}""#content {""tpadding: 0 12px 12px;""}""#overview table {""tmax-width: 75;""twidth: auto;""}""#messages table {""twidth: 97;""}""</style>""</head>""<body>""<div id="big_wrapper">""t<h1>Test Results - {@testdesc}</h1>""t<table>""{@eeddata}""t</table>""</body>""</html>";
};
};
На самом деле не знаю, что я делаю здесь не так …
Это ошибка, которую я получаю:
Ошибка 2 ошибка C2086: ‘const char * DataVerifier :: Structure :: strHTMLTemplate’: переопределение c: users suzan documents visual studio 2013 projects test1 test1 testconstantsheader.cpp 7 1 Test1
Ошибка 3 ошибка C2086: ‘const char * DataVerifier :: Structure :: strHTMLTemplate’: переопределение c: users suzan documents visual studio 2013 projects test1 test1 testconstantsheader.cpp 7 1 Test1
0
Решение
Ваш заголовочный файл содержит определение объекта strHTMLTemplate
с внешней связью. Это то, что приводит к множественной ошибке определения.
Изменить определение strHTMLTemplate
в заголовочном файле в не определяющая декларация добавив ключевое слово extern
// TestConstantsHeader.h
namespace DataVerifier
{
namespace Structure
{
extern const char *strHTMLTemplate;
}
}
Кроме того, вероятно, имеет смысл объявить указатель как const char *const strHTMLTemplate
, Это не похоже, что это должно быть изменяемым.
3
Другие решения
- Remove From My Forums
-
Вопрос
-
Hello,
I added my header file in MyProject.cpp as
#include "MyProject.h"
But when I go to add my int definition into MyProject.h
Visual Studio does not compile and shows:
Error 1 error C2086: 'int users' : redefinition
In MyProject.cpp, variable users is declared as:
int users = 245;
So why I am getting this error and how can I fix it?
Strangely this issue only happens for int variables?
Function definitions do not create any issue in header file for compilation?Cheers
Ответы
-
Do like this
MyProject.h file #pragma once extern int users; // declaration wchar_t *subStr(wchar_t *string, int position, int length);
MyProject.cpp file int users = 1; // definition wchar_t *subStr(wchar_t *string, int position, int length) { return string + position; // or other definition }
Only put declarations in header files, not definitions.
David Wilkinson | Visual C++ MVP
-
Помечено в качестве ответа
22 марта 2016 г. 9:51
-
Помечено в качестве ответа
Вопрос
Это мой CPP-код:
#include <iostream>
#include <string>
#include <array>
#include <cmath>
using namespace std;
/*
bool func1(int budget){
if( budget < 0 ) {
cout << "Budget cannot be negative."<< endl;
return false;
}
else {
return true;
}
}
bool func2(int num1, int num2, int num3){
if (int num1 < 0 || int num2 < 0 || int num3 < 0 ) {
cout << "All quantities must be positive."<< endl;
return false;
}
else {
return true;
}
}
*/
int func3(int *p, int index){
int currentprice = *(p) * 5 + *(p+1) * 10 + *(p+2) * 15 ;
return currentprice;
}
int manin() {
int budget;
int num1, num2, num3;
int p1;
int p2;
int p3;
int currentprice;
int func3;
cin >> p1 >> p2 >> p3 ;
int position[3] ;
position[0] = p1 ;
position[1] = p2 ;
position[2] = p3 ;
int *p;
p= position;
int func3(currentprice);
cout << currentprice;
return 0;
}
Это ошибка, которую я получаю :
1>------ Build started: Project: ConsoleApplication3, Configuration: Debug Win32 ------
1> Source.cpp
1>c:usersnonameonedrivemasaüstücsconsoleapplication3consoleapplication3source.cpp(56): error C2086: 'int func3' : redefinition
1> c:usersnonameonedrivemasaüstücsconsoleapplication3consoleapplication3source.cpp(48) : see declaration of 'func3'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
пожалуйста, не могли бы вы помочь мне с мастерами CPP?
3
Полезно начинать с определенной цели. Что вы пытаетесь сделать, не очень понятно.
int func3(int *p, int index)
является функцией и int func3
является переменной величиной. Вот в чем заключается ваша ошибка. Вы можете переименовать переменную, чтобы избежать этой ошибки.
Кроме того, это неправильный способ вызова функции: int func3(currentprice);
. Во-первых, эта функция принимает два параметра вместо одного. Во-вторых, возвращаемое значение нигде не хранится.
Кроме того, консольная программа начнет выполняться с main
функция. Так manin
вероятно, должно быть main
.
Этот…
int func3;
… является декларацией о func3
в качестве переменной типа int
. Он затеняет объявление функции в области действия файла func3()
.
Этот…
int func3(currentprice);
… также является декларацией о func3
(не вызов функции) из-за int
спереди. Вы не можете повторно объявлять локальную переменную func3
в одной и той же области, даже если два объявления обозначают один и тот же тип.
Удалите int func3;
в целом. Также удалите int
От int func3(currentprice);
.
@JohnBollinger @DKS @JohnnyMopp @DrewDormann @ThomasMatthews
Ребята, я исправил это с помощью ваших предложений, это приводит к успеху. Тем не менее, это должно занять 3 cin(p1,p2,p3) и должно указывать на текущую цену, вместо этого она показывает пустое значение.
Я добавляю новые коды ниже:
#include <iostream>
#include <string>
#include <array>
#include <cmath>
using namespace std;
/*
bool func1(int budget){
if( budget < 0 ) {
cout << "Budget cannot be negative."<< endl;
return false;
}
else {
return true;
}
}
bool func2(int num1, int num2, int num3){
if (int num1 < 0 || int num2 < 0 || int num3 < 0 ) {
cout << "All quantities must be positive."<< endl;
return false;
}
else {
return true;
}
}
*/
int func3(int *p){
int currentprice = *(p) * 5 + *(p+1) * 10 + *(p+2) * 15 ;
return currentprice;
}
int main() {
/*
int budget;
int num1, num2, num3;
*/
int p1;
int p2;
int p3;
int currentprice= 0;
cin >> p1 >> p2 >> p3 ;
int position[3] ;
position[0] = p1 ;
position[1] = p2 ;
position[2] = p3 ;
int *p;
p= position;
func3(p);
cout << currentprice;
return 0;
}
На других языках
Эта страница на других языках
empty row
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
Популярное в этой категории
Популярные вопросы в этой категории
Обновлено
Вопрос:
Я получаю ошибку C2086 из Visual Studio при попытке объявить переменную в пространстве имен, определить ее в одном файле кода и получить к ней доступ в другом файле кода.
При создании с помощью gcc (из кодовых блоков) ошибка (… == путь на моем жестком диске):
… file_one.cpp | 2 | ошибка: переопределение “RecvVarProxyFn Skins :: fnSequenceProxyFn”
… file_one.h | 4 | note: ‘RecvVarProxyFn Skins :: fnSequenceProxyFn’, ранее объявленный здесь
Даже при деактивации (используя //
) линии доступа в main() ошибка одинакова.
file_one.h:
typedef int RecvVarProxyFn;
namespace Skins {
RecvVarProxyFn fnSequenceProxyFn; // "previously declared here"
}
file_one.cpp
#include "file_one.h"
RecvVarProxyFn Skins::fnSequenceProxyFn = 0; // redefinition error 2086
main.cpp
#include "file_one.h"
int main()
{ Skins::fnSequenceProxyFn = 1; // making this a comment does not help
return 0;
}
Почему я получаю ошибку переопределения для моей попытки определить переменную в отдельном файле кода?
НОТА:
Я использую visual studio 2015 Target Platform для версии 8.1
и набор инструментов платформы, установленный в v140
.
Лучший ответ:
Используйте ключевое слово extern
для изменения одного из определений в декларации.
Очевидно, что строка в заголовке является первым выбором.
namespace Skins {
extern RecvVarProxyFn fnSequenceProxyFn;
}
Вопрос
Это мой CPP-код:
#include <iostream>
#include <string>
#include <array>
#include <cmath>
using namespace std;
/*
bool func1(int budget){
if( budget < 0 ) {
cout << "Budget cannot be negative."<< endl;
return false;
}
else {
return true;
}
}
bool func2(int num1, int num2, int num3){
if (int num1 < 0 || int num2 < 0 || int num3 < 0 ) {
cout << "All quantities must be positive."<< endl;
return false;
}
else {
return true;
}
}
*/
int func3(int *p, int index){
int currentprice = *(p) * 5 + *(p+1) * 10 + *(p+2) * 15 ;
return currentprice;
}
int manin() {
int budget;
int num1, num2, num3;
int p1;
int p2;
int p3;
int currentprice;
int func3;
cin >> p1 >> p2 >> p3 ;
int position[3] ;
position[0] = p1 ;
position[1] = p2 ;
position[2] = p3 ;
int *p;
p= position;
int func3(currentprice);
cout << currentprice;
return 0;
}
Это ошибка, которую я получаю :
1>------ Build started: Project: ConsoleApplication3, Configuration: Debug Win32 ------
1> Source.cpp
1>c:\users\noname\onedrive\masaüstü\cs\consoleapplication3\consoleapplication3\source.cpp(56): error C2086: 'int func3' : redefinition
1> c:\users\noname\onedrive\masaüstü\cs\consoleapplication3\consoleapplication3\source.cpp(48) : see declaration of 'func3'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
пожалуйста, не могли бы вы помочь мне с мастерами CPP?
3
Полезно начинать с определенной цели. Что вы пытаетесь сделать, не очень понятно.
int func3(int *p, int index)
является функцией и int func3
является переменной величиной. Вот в чем заключается ваша ошибка. Вы можете переименовать переменную, чтобы избежать этой ошибки.
Кроме того, это неправильный способ вызова функции: int func3(currentprice);
. Во-первых, эта функция принимает два параметра вместо одного. Во-вторых, возвращаемое значение нигде не хранится.
Кроме того, консольная программа начнет выполняться с main
функция. Так manin
вероятно, должно быть main
.
Этот…
int func3;
… является декларацией о func3
в качестве переменной типа int
. Он затеняет объявление функции в области действия файла func3()
.
Этот…
int func3(currentprice);
… также является декларацией о func3
(не вызов функции) из-за int
спереди. Вы не можете повторно объявлять локальную переменную func3
в одной и той же области, даже если два объявления обозначают один и тот же тип.
Удалите int func3;
в целом. Также удалите int
От int func3(currentprice);
.
@JohnBollinger @DKS @JohnnyMopp @DrewDormann @ThomasMatthews
Ребята, я исправил это с помощью ваших предложений, это приводит к успеху. Тем не менее, это должно занять 3 cin(p1,p2,p3) и должно указывать на текущую цену, вместо этого она показывает пустое значение.
Я добавляю новые коды ниже:
#include <iostream>
#include <string>
#include <array>
#include <cmath>
using namespace std;
/*
bool func1(int budget){
if( budget < 0 ) {
cout << "Budget cannot be negative."<< endl;
return false;
}
else {
return true;
}
}
bool func2(int num1, int num2, int num3){
if (int num1 < 0 || int num2 < 0 || int num3 < 0 ) {
cout << "All quantities must be positive."<< endl;
return false;
}
else {
return true;
}
}
*/
int func3(int *p){
int currentprice = *(p) * 5 + *(p+1) * 10 + *(p+2) * 15 ;
return currentprice;
}
int main() {
/*
int budget;
int num1, num2, num3;
*/
int p1;
int p2;
int p3;
int currentprice= 0;
cin >> p1 >> p2 >> p3 ;
int position[3] ;
position[0] = p1 ;
position[1] = p2 ;
position[2] = p3 ;
int *p;
p= position;
func3(p);
cout << currentprice;
return 0;
}
На других языках
Эта страница на других языках
empty row
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………
……………………………………………………………………………………………………