expected identifier before string constant - c++

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

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;
}

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.

Related

In function int main(): class name was not declared in this scope

Im using vscode and im new to c++. I learned how to create a header file link to its cpp and use it to main.cpp. The only problem bugs me out is why it causes an error this is my simple code.
Name.h
#include <iostream>
#include <string>
class myname
{
public:
void setname(std::string name);
void prname();
private:
std::string Name;
};
Name.cpp
#include "Name.h"
void myname::setname(std::string name)
{
Name = name;
}
void myname::prname()
{
std::cout<<"Hello :"<<Name<<std::endl;
}
Maiin.cpp
#include <iostream>
#include <string>
#include "Name.h"
using std::cout;
using std::string;
using std::endl;
int main()
{
myname Epoy; // IN FUNCTION INT MAIN: ERROR myname was not declared in this scope
Epoy.setname("Jomar"); //note myname <-rename "BUT THIS IS NOT THE ERROR CAUSE THIS JUST HAPPEN BECAUSE OF THE ERROR ABOVE "
Epoy.prname();
return 0;
}
also i tried so many method i even compiled this by using g++ Maiin.cpp Name.cpp - o Maiin
Still didnt work
Edit: Community want me to add more details.
What I asked was, have you write header guards in your header file: #ifndef Name_H, #define Name_H, #endif ? Since you use vscode you have to done it manually.
Like this:
#ifndef Name_H
#define Name_H
#include <iostream>
#include <string>
class myname
{
public:
void setname(std::string name);
void prname();
private:
std::string Name;
};
#endif
you missing a C++ constructor:
class Foo {
public:
Foo() { /* your init code */ } // <-- this is a std. C++ constructor
~Foo() { /* your clean-up code */ } // <-- this is a std. C++ de-structor
};
int main(int argc, char **argv) {
Foo bar; // here, you don't need the: ( ) object on heap !
}

No constructor for class C++ using class as java enum

i'm recently starting with c++ and I'm having troubles when I want to use a c++ class like Java's enums.
I would have the 'simulated enum' class attribute, but when I try to initialize the attribute in the constructor i received the following error:
no default constructor exists for model::suite
I now I have the constructor private, but the enum should have private constructors to prevent the construction of undefined objects of that class.
¿What should I do?
e.g.
suite.h
#include <iostream>
#include <string>
#include <vector>
namespace model
{
class Suite
{
public:
static const Suite CLUBS;
static const Suite DIAMONDS;
static const Suite SPADES;
static const Suite HEARTS;
static const int SIZE = 4;
private:
std::string name;
Suite(std::string name)
{
this->name = name;
}
public:
std::string toString()
{
return name;
}
std::vector<Suite> values()
{
return {Suite::CLUBS, Suite::DIAMONDS, Suite::SPADES, Suite::HEARTS};
}
};
const Suite Suite::CLUBS = Suite("CLUBS");
const Suite Suite::DIAMONDS = Suite("DIAMONDS");
const Suite Suite::SPADES = Suite("SPADES");
const Suite Suite::HEARTS = Suite("HEARTS");
}
card.h
#pragma once
#include <string>
#include "suite.h"
#include "face.h"
namespace model
{
class Card
{
public:
Card(int face, int suite);
Face getFace();
Suite getSuite();
bool isMergeable();
std::string toString();
private:
Face face;
Suite suite;
bool isRed();
bool isContigous(Card card);
};
}
card.cpp
#include <iostream>
#include "card.h"
using namespace std;
using namespace model;
Card::Card(int face, int suite)
{
this->face = Face::VALUES[face];
}
Face Card::getFace()
{
}
Suite Card::getSuite()
{
}
bool Card::isMergeable()
{
}
std::string Card::toString()
{
}
bool Card::isRed()
{
}
bool Card::isContigous(Card card)
{
}
Well finally I found a solution.
When we try to implement the 'simulated enum' on the cpp file, we have the this-> pointer and also the scope who envolves it (scope rules), so we need to define the object before the { } of the constructor.
#include <iostream>
#include "card.h"
using namespace std;
using namespace model;
Card::Card(Face face, Suite suite) : face(face), suite(suite)
{
}
That way we could implement a stronger and useful enums with attributes and methods.

Boost test setup error: memory access violation

I am getting the above error while running the executable after compiling and running the following file.
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/test/unit_test_log.hpp>
#include <boost/filesystem/fstream.hpp>
#include "index/DatabaseGroup.hpp"
using namespace boost::unit_test;
namespace indexing {
class ForwardDBTest {
/// A pointer to the database group object.
DatabaseGroup& databaseGroup;
std::string databaseName;
public:
~ForwardDBTest() {
}
;
ForwardDBTest(DatabaseGroup& databaseGroup_, std::string dbName) :
databaseGroup(databaseGroup_), databaseName(dbName) {
}
void boostTestCreateDB() {
databaseGroup.createDatabase(databaseName, databaseName);
}
};
class testSuites: public test_suite {
public:
testSuites() :
test_suite("test_suite") {
std::string db_location = "home/girijag/ripe/ripe_db";
std::cout << "hello" << std::endl;
int concurrency = 0;
std::string db_cache_policy = "AllMem";
boost::shared_ptr<DatabaseGroup> db = boost::shared_ptr<DatabaseGroup>(
new DatabaseGroup(db_location, concurrency, db_cache_policy));
std::string dbName = "DB1";
boost::shared_ptr<ForwardDBTest> instance(
new ForwardDBTest(*db, dbName));
test_case* boostTestCreateDB_test_case = BOOST_CLASS_TEST_CASE(
&ForwardDBTest::boostTestCreateDB, instance);
add(boostTestCreateDB_test_case);
}
~testSuites() {
}
;
};
test_suite* init_unit_test_suite(int argc, char** argv) {
test_suite* suite(BOOST_TEST_SUITE("Master Suite"));
suite->add(new testSuites());
return suite;
}
}'
Please let me know how should i resolve this?
i am getting errors as below:-
Test setup error: memory access violation at address: 0x00000021: no mapping at fault address
I have been struggling from past 2 days to figure out whats my issue
There are a number of disturbing things in the code, and some formatting seems have to been lost when posting the question, otherwise there is no chance it compiles. (For example, }’ ?!)
For starters, you shouldn’t place init_unit_test_suite(int, char**) in the indexing namespace, and subsequently there is no point in defining BOOST_TEST_MAIN - you will end up with multiple definition of the said init_unit_test_suite(int, char**) method.
In your case, the suite should be simply registered in the master test suite, there is no need to return a pointer to it from the method.
Here’s a minimal example that you can work with an extend for your purpose. It follows your structure, but omits non-relevant details:
#include <boost/test/included/unit_test.hpp>
#include <iostream>
using namespace boost::unit_test;
namespace indexing {
class ForwardDBTest {
public:
void boostTestCreateDB() { std::cout << __FUNCTION__ << std::endl; }
};
class TestSuite : public test_suite {
public:
TestSuite() : test_suite("test_suite") {
boost::shared_ptr<ForwardDBTest> instance(new ForwardDBTest);
add(BOOST_CLASS_TEST_CASE(&ForwardDBTest::boostTestCreateDB, instance));
}
};
} // namespace indexing
test_suite* init_unit_test_suite(int, char**) {
framework::master_test_suite().add(new indexing::TestSuite);
return 0;
}
/* Output:
Running 1 test case...
boostTestCreateDB
*** No errors detected
*/

Copy constructor error c2039

hy guys! I have a code that gives me headaches. I would like some help please. This is my .h file.
#include <iostream>
#include <string>
using namespace std;
namespace UI{
class Comanda
{
private:
const string _nume;
public:
Comanda();
Comanda(const string &nume);
virtual ~Comanda();
const string& Nume() const;
virtual void AsteaptaEnter();
virtual void Execute();
};
};
And the .cpp:
#include <iostream>
#include <string>
#include "Comanda.h"
#include "Exceptii.h"
using namespace std;
using namespace UI;
Comanda::Comanda()
{
cout << "Comanda()" << endl;
}
Comanda::Comanda(const string &nume)
{
_nume = nume._nume;
}
The compiler shows me this error:
error C2039: '_nume' : is not a member of 'std::basic_string<_Elem,_Traits,_Ax>'
What should i do? Thanks in advance!
You must initialize the constant members in the initializer list of ctor, and also nume._nume is not valid.
Comanda::Comanda(const string &nume) : _nume(nume) {}
^^^^^^^^^^^^^
You probably meant
Comanda::Comanda(const string &nume)
{
_nume = nume;
}
It's not a copy constructor by the way.
_nume = nume._nume; this is wrong
it should be _nume = nume;
And as correctly pointed out by #Cornstalks you cannot achieve above assignments in any case as _nume is const.

C++ - Declaration of method incompatible

EDIT:
I'm using namespace std
I'm using VS10
Room is a separate class
I've included the memory header in all necessary files
The original error was an Intellisense error I was getting before building. After building, I got a buttload more:
[The original Intellisense error before building] declaration is incompatible with "std::tr1::shared_ptr<< error-type >> Option::getRoom()
'std::tr1::shared_ptr<_Ty> Option::getRoom(void)' : overloaded function differs only by return type from 'std::tr1::shared_ptr Option::getRoom(void)'
'Option::getRoom' : redefinition; different basic types
'Option::getRoom' uses undefined class 'std::tr1::shared_ptr'
These are related to this piece of code in Option.cpp:
shared_ptr<Room> Option::getRoom(){
shared_ptr<Room> room(new Room);
return room;
}
The corresponding code in Option.hpp:
public:
virtual shared_ptr<Room> getRoom();
Error 'RoomOption::getRoom': overriding virtual function return type differs and is not covariant from 'Option::getRoom'
[IntelliSense] return type is not identical to nor covariant with return type "std::tr1::shared_ptr<< error-type >>" of overridden virtual function function "Option::getRoom"
This is related to this piece of code in RoomOption.hpp, a subclass of Option:
public:
shared_ptr<Room> getRoom();
Here's all the code from the two classes I'm having trouble with:
Option.h:
#pragma once
#include "Room.h"
#include <memory>
using namespace std;
class Option
{
protected:
int id;
char* text;
public:
Option(void);
Option(int, char*);
virtual ~Option(void);
char* getText();
int getID();
virtual shared_ptr<Room> getRoom();
};
Option.cpp:
#include "Option.h"
#include "Room.h"
#include <memory>
using namespace std;
Option::Option(void)
{
}
Option::Option(int newID, char* newText){
id = newID;
text = newText;
}
Option::~Option(void)
{
}
char* Option::getText(){
return text;
}
int Option::getID(){
return id;
}
shared_ptr<Room> Option::getRoom(){
shared_ptr<Room> room(new Room());
return room;
//note that this function will never be used. I'd prefer to
//pass back a null pointer but I couldn't do that either.
}
RoomOption.h:
#pragma once
#include "Option.h"
#include "Room.h"
#include <memory>
using namespace std;
class RoomOption :
public Option
{
private:
shared_ptr<Room> room;
public:
RoomOption(void);
RoomOption(int, char*, shared_ptr<Room>);
~RoomOption(void);
void setRoom(shared_ptr<Room>);
shared_ptr<Room> getRoom();
};
RoomOption.cpp:
#include "RoomOption.h"
#include "Room.h"
#include <memory>
using namespace std;
RoomOption::RoomOption(void)
{
}
RoomOption::RoomOption(int newID, char* newText, shared_ptr<Room> newRoom)
{
id = newID;
strcpy(text, newText);
room = newRoom;
}
RoomOption::~RoomOption(void)
{
}
void RoomOption::setRoom(shared_ptr<Room> newRoom){
room = newRoom;
}
shared_ptr<Room> RoomOption::getRoom(){
return room;
}
This code compiles without error at /W4 /WX with VS 2010:
#include <memory>
struct Room {};
class Option {
public:
std::shared_ptr<Room> getRoom();
};
std::shared_ptr<Room> Option::getRoom(){
std::shared_ptr<Room> room(new Room());
return room;
}
int main() {
Option opt;
std::shared_ptr<Room> room = opt.getRoom();
return 0;
}
What are you doing differently?
Is Room declared at the point where it's used in the getRoom() call in Option.hpp?
Have you tried removing the () from new Room() in case you're somehow getting hit by the most vexing parse, possibly in other code we can't see??