Having a program like this:
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(std::string s):str(s){};
private:
std::string str;
};
class test1
{
public:
test tst_("Hi");
};
int main()
{
return 1;
}
…why am I getting the following when I execute
g++ main.cpp
main.cpp:16:12: error: expected identifier before string constant
main.cpp:16:12: error: expected ‘,’ or ‘...’ before string constant
asked Apr 7, 2012 at 5:46
2
You can not initialize tst_
where you declare it. This can only be done for static const
primitive types. Instead you will need to have a constructor for class test1
.
EDIT: below, you will see a working example I did in ideone.com. Note a few changes I did. First, it is better to have the constructor of test
take a const
reference to string
to avoid copying. Second, if the program succeeds you should return 0
not 1
(with return 1
you get a runtime error in ideone).
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(const std::string& s):str(s){};
private:
std::string str;
};
class test1
{
public:
test1() : tst_("Hi") {}
test tst_;
};
int main()
{
return 0;
}
answered Apr 7, 2012 at 5:49
Ivaylo StrandjevIvaylo Strandjev
68.4k18 gold badges123 silver badges173 bronze badges
2
There is another and more simplified way of doing what you want:Just change your statement from test tst_("Hi");
to test tst_{"Hi"};
and it will work. Below is the modified code and it works as expected.
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(std::string s):str(s){cout<<"str is: "<<s;}
private:
std::string str;
};
class test1
{
public:
test tst_{"Hi"};
};
int main()
{ test1 obj;
return 0;
}
Note that i have just changed test tst_("Hi");
to test tst_{"Hi"};
and everything else is exactly the same. Just for confirmation that this works i have added one cout to check that it initialize the str variable correctly. I think this one line solution is more elegant(at least to me) and and up to date with the new standard.
answered Feb 21, 2021 at 16:23
Jason LiamJason Liam
32.4k5 gold badges21 silver badges52 bronze badges
2
Содержание
- ожидаемый идентификатор перед строковой константой
- 2 ответы
- Error expected identifier before string constant
- Error expected identifier before string constant
- Error expected identifier before string constant
- C / C++ / MFC
ожидаемый идентификатор перед строковой константой
Наличие такой программы:
…почему я получаю следующее при выполнении
Вы действительно должны научиться всегда компилировать с g++ -Wall -g — Basile Starynkevitch
2 ответы
Вы не можете инициализировать tst_ где вы это декларируете. Это можно сделать только для static const примитивные виды. Вместо этого вам понадобится конструктор для class test1 .
РЕДАКТИРОВАТЬ: ниже вы увидите рабочий пример, который я сделал в ideone.com. Обратите внимание на несколько изменений, которые я сделал. Во-первых, лучше иметь конструктор test взять const ссылка на string во избежание копирования. Во-вторых, если программа успешна, вы должны return 0 не 1 (с return 1 вы получаете ошибку времени выполнения в идеона).
ответ дан 30 окт ’21, 00:10
Есть еще один и более упрощенный способ сделать то, что вы хотите: просто измените свое утверждение с test tst_(«Hi»); в test tst_<«Hi»>; и это будет работать. Ниже приведен модифицированный код, и он работает так, как ожидалось.
Обратите внимание, что я только что изменил test tst_(«Hi»); в test tst_<«Hi»>; а все остальное точно так же. Просто для подтверждения того, что это работает, я добавил один cout, чтобы проверить, правильно ли он инициализирует переменную str. Я думаю, что это однострочное решение более элегантно (по крайней мере, для меня) и соответствует новому стандарту.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками c++ linux constructor or задайте свой вопрос.
Источник
Error expected identifier before string constant
I’m a a pretty new programmer just beginning to play around with C and C++. I use Linux and am compiling with gcc/g++ 4.3.2 however I’m coming across a strange problem that I just can’t resolve.
I’m trying to write a simple program to just see the possibilities of calling C++ code from C. The main() function is in C :
The function cpp_main() is written in C++, and is in file cpp_main.cpp :
And cpp_main.h is :
However when I try to build the executable I receive this error :
cpp_main.h:6: error: expected identifier or ‘(’ before string constant
gcc is telling me there is something wrong with extern «C». .
If I take the line from the header file and paste it directly into cpp_main.cpp everything compiles and links ok. but why won’t it work with the header file ?
Any help is much appreciated
I’ll try to guess the problem.
The block
extern «C»
<
.
>
need not a final semicolon.
You also may use the difinition of the form
extern «C» void cpp_main(int argc, char** argv);
if you declare the only function.
But worse thing is that the definition in the cpp_main.h differs from that in the cpp_main.cpp in the returned type (void vs int).
OK, well as in my original post, can you explain why this compiles :
Yet if I separate decelerations into a header file, this does NOT compile, giving the error I originally stated :
I’m using gcc and it has the capability to determine the source type (C or C++) from the file extension and passes it to the appropriate compiler in the toolchain, therefore I do not believe it’s a problem due to trying to compile C++ with a C compiler.
I was playing round with the return type and forgot to put it back before quoting the code here in the forum. Also it’s not because I didn’t have a semi-colon after the ‘extern’ decleration.
i succeeded in compiling your code with *.h and *.cpp files
with gcc version 3.4.6 20060404 (Red Hat 3.4.6-10)
Are you sure the problem is in compiling (gcc -c cpp_main.cpp), not in linking? Otherwise it’s another problem.
I managed to solve the problem — I had included a C++ header in the C file which contains main() (as you’ll see from my original post)
I had a misunderstanding of the use of headers — I thought they were there to enable the linker to resolve references to functions in other files. I was therefore skeptical at first removing the C++ #include expecting an ‘unresolved function’ error — but no gcc doesn’t necessarily use headers to resolve
Thanks for your help though.. tis much appreciated by a newbie !
Источник
Error expected identifier before string constant
Write your question here.
its a global object of type A or more likely a static
@sail456852
you cannot define an object inside a class,
define it in constructor or in other member function.
Line 8: The compiler thinks that is a function declaration that returns a const string.
Try this instead:
> The compiler thinks that is a function declaration that returns a const string.
No, there is no MVP here. ( «I am a bitch adsadfadf» is not the name of a type).
Only a brace-or-equal initializer is allowed for an in-class member initializer.
Any one of these would be fine:
With C++11 you can initialize class members like this, too
@Lorence30: Thanks, I learn so much from this site!
@andywestken: I really need to get more into C++11!
I summarized what I’ve learned about string initialisation,and tested each form declaration in class and global respectively :
1.All 4 forms work out okay in global declaration
2.Only public1 compilation error in class initialisation ! .
I wanna know a little deeper about this :
as I know ,string a class itself .
okay. I should yahoo it .
Источник
Error expected identifier before string constant
I’m building a fraction calculator in C++ & I’ve ran into the error: «expected ‘;’ before string constant» & I can’t figure out whats wrong with it. Here is my code:
_______________________________________________________________________________
int FracPer () <
cout > numer1;
cout > denom1;
frac1 = numer1 «/» denom1;
percent = (numer1 / denom1) * 100;
cout
frac1 = numer1 «/» denom1;
What is that meant for? It’s causing the error.
If you’re trying to concatenate strings, the syntax to do so with std::string type is «+», as in
frac1 = numer1 + «/» + denom1;
Ah, if only C++ was PERL. 😉
For this to work, you will need to make a cast from a string type (like std::string) to an integral type, or vice-versa. C++ won’t implicitly convert between them.
Here’s a way to convert from an int into a string (I’m assuming numer1 and denom1 are numeric).
http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/
P.S: Are numer1 and denom1 ints? If they are, you might have some problems with the division.
EDIT: Did anyone else notice that none of these variables seem to be declared in this function? Or am I just missing it?
Источник
C / C++ / MFC
Last Visit: 31-Dec-99 19:00 Last Update: 15-Jan-23 4:45 | Refresh | ᐊ Prev1 . 189190191192 193 194195196197198 Next ᐅ |
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
Источник
Extern «C» problem
Hello,
I’m a a pretty new programmer just beginning to play around with C and C++. I use Linux and am compiling with gcc/g++ 4.3.2 however I’m coming across a strange problem that I just can’t resolve.
I’m trying to write a simple program to just see the possibilities of calling C++ code from C. The main() function is in C :
|
|
The function cpp_main() is written in C++, and is in file cpp_main.cpp :
|
|
And cpp_main.h is :
|
|
However when I try to build the executable I receive this error :
cpp_main.h:6: error: expected identifier or ‘(’ before string constant
gcc is telling me there is something wrong with extern «C»… ?!?!!?
If I take the line from the header file and paste it directly into cpp_main.cpp everything compiles and links ok… but why won’t it work with the header file ?
Any help is much appreciated
Steve
I’ll try to guess the problem.
The block
extern «C»
{
…
}
need not a final semicolon.
You also may use the difinition of the form
extern «C» void cpp_main(int argc, char** argv);
if you declare the only function.
But worse thing is that the definition in the cpp_main.h differs from that in the cpp_main.cpp in the returned type (void vs int).
Also, extern «C» is only defined in C++ compiliers, so if you are compiling with a C compilier, you can’t compile it. Put #ifdef _cplusplus
(I think) around it with correct #endif
s.
Firedraco :
OK, well as in my original post, can you explain why this compiles :
|
|
Yet if I separate decelerations into a header file, this does NOT compile, giving the error I originally stated :
cpp_main.h
|
|
cpp_main.cpp
|
|
I’m using gcc and it has the capability to determine the source type (C or C++) from the file extension and passes it to the appropriate compiler in the toolchain, therefore I do not believe it’s a problem due to trying to compile C++ with a C compiler.
melkiy:
I was playing round with the return type and forgot to put it back before quoting the code here in the forum. Also it’s not because I didn’t have a semi-colon after the ‘extern’ decleration.
i succeeded in compiling your code with *.h and *.cpp files
with gcc version 3.4.6 20060404 (Red Hat 3.4.6-10)
Are you sure the problem is in compiling (gcc -c cpp_main.cpp), not in linking? Otherwise it’s another problem.
Last edited on
melkiy:
I managed to solve the problem — I had included a C++ header in the C file which contains main() (as you’ll see from my original post)
I had a misunderstanding of the use of headers — I thought they were there to enable the linker to resolve references to functions in other files. I was therefore skeptical at first removing the C++ #include expecting an ‘unresolved function’ error — but no gcc doesn’t necessarily use headers to resolve
Thanks for your help though.. tis much appreciated by a newbie !
Topic archived. No new replies allowed.
Bangemin 0 / 0 / 1 Регистрация: 06.11.2015 Сообщений: 99 |
||||
1 |
||||
Ошибка при создании обьекта класса06.05.2016, 11:18. Показов 2449. Ответов 6 Метки нет (Все метки)
Объясните пожалуйста почему нельзя создать обьект другого класса в private. В чем ошибка ? Код:
__________________
0 |
Lawliet1 31 / 34 / 18 Регистрация: 30.09.2011 Сообщений: 202 |
||||||||
06.05.2016, 11:29 |
2 |
|||||||
Сообщение было отмечено Bangemin как решение Решениевсе поля внутри объекта инициализируются после создания объекта… правильней переписать ваш код так:
тут используется внутриклассовая инициализация, если ваш компилятор не поддерживает 11 стандарт, то нужно переписать программу как-то так:
1 |
0 / 0 / 1 Регистрация: 06.11.2015 Сообщений: 99 |
|
06.05.2016, 11:32 [ТС] |
3 |
Большое спасибо, за помощь
0 |
Bangemin 0 / 0 / 1 Регистрация: 06.11.2015 Сообщений: 99 |
||||||||||||
08.05.2016, 10:58 [ТС] |
4 |
|||||||||||
Как можно грамотно инициализировать в производном классе объект другого класса ? Вот код:
0 |
4AKE 29 / 29 / 18 Регистрация: 20.12.2010 Сообщений: 119 |
||||
08.05.2016, 18:34 |
5 |
|||
0 |
0 / 0 / 1 Регистрация: 06.11.2015 Сообщений: 99 |
|
08.05.2016, 21:29 [ТС] |
6 |
не не то, мне нужно чтобы storage передавал storage.txt вместо .txt, или как-то так
0 |
4AKE 29 / 29 / 18 Регистрация: 20.12.2010 Сообщений: 119 |
||||
08.05.2016, 21:35 |
7 |
|||
Сообщение было отмечено Bangemin как решение РешениеBangemin,
1 |
ожидаемый идентификатор перед строковой константой
Наличие такой программы:
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(std::string s):str(s){};
private:
std::string str;
};
class test1
{
public:
test tst_("Hi");
};
int main()
{
return 1;
}
…почему я получаю следующее при выполнении
g ++ main.cpp
main.cpp:16:12: error: expected identifier before string constant
main.cpp:16:12: error: expected ‘,’ or ‘...’ before string constant
Вы не можете инициализировать tst_
где вы это декларируете. Это можно сделать только для static const
примитивные виды. Вместо этого вам понадобится конструктор для class test1
.
РЕДАКТИРОВАТЬ: ниже вы увидите рабочий пример, который я сделал в ideone.com. Обратите внимание на несколько изменений, которые я сделал. Во-первых, лучше иметь конструктор test
взять const
ссылка на string
во избежание копирования. Во-вторых, если программа успешна, вы должны return 0
не 1
(с return 1
вы получаете ошибку времени выполнения в идеона).
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(const std::string& s):str(s){};
private:
std::string str;
};
class test1
{
public:
test1() : tst_("Hi") {}
test tst_;
};
int main()
{
return 0;
}
ответ дан 30 окт ’21, 00:10
Есть еще один и более упрощенный способ сделать то, что вы хотите: просто измените свое утверждение с test tst_("Hi");
в test tst_{"Hi"};
и это будет работать. Ниже приведен модифицированный код, и он работает так, как ожидалось.
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(std::string s):str(s){cout<<"str is: "<<s;}
private:
std::string str;
};
class test1
{
public:
test tst_{"Hi"};
};
int main()
{ test1 obj;
return 0;
}
Обратите внимание, что я только что изменил test tst_("Hi");
в test tst_{"Hi"};
а все остальное точно так же. Просто для подтверждения того, что это работает, я добавил один cout, чтобы проверить, правильно ли он инициализирует переменную str. Я думаю, что это однострочное решение более элегантно (по крайней мере, для меня) и соответствует новому стандарту.
Создан 21 фев.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
c++
linux
constructor
or задайте свой вопрос.
Hello,
I’m a a pretty new programmer just beginning to play around with C and C++. I use Linux and am compiling with gcc/g++ 4.3.2 however I’m coming across a strange problem that I just can’t resolve.
I’m trying to write a simple program to just see the possibilities of calling C++ code from C. The main() function is in C :
Code:
#include <stdio.h> #include <stdlib.h> #include "cpp_main.h" /* * */ int main(int argc, char** argv) { int return_value; return_value = cpp_main(argc,argv); return (return_value); }The function cpp_main() is written in C++, and is in file cpp_main.cpp :
Code:
#include "cpp_main.h" //#include "testclass.h" //int cpp_main(int argc, char** argv); /*extern "C" { int cpp_main(int argc, char** argv); }*/ int cpp_main(int argc, char** argv){ char *testtext = "Some Test Text to display.n"; //TestClass::WriteMessage(testtext); return(0); }And cpp_main.h is :
Code:
//#ifndef _CPP_MAIN_H //#define _CPP_MAIN_H // Declare cpp_main() function //int cpp_main(int argc, char** argv); extern "C" { void cpp_main(int argc, char** argv); }; //#endif /* _CPP_MAIN_H */However when I try to build the executable I receive this error :
cpp_main.h:6: error: expected identifier or �(� before string constant
gcc is telling me there is something wrong with extern «C»… ?!?!!?
If I take the line from the header file and paste it directly into cpp_main.cpp everything compiles and links ok… but why won’t it work with the header file ?
Any help is much appreciated
Steve