I have this code:
hpp:
#include <list>
using namespace std;
class funcionario
{
public:
struct Dia {
int d;
int h;
int id;
int tipo;
};
funcionario ();
void eliminar(int dia, int hora);
private:
list<Dia> agenda;
};
cpp:
#include "myClass.hpp"
funcionario::funcionario(){
agenda = list<Dia> ();
}
void funcionario::eliminar(int dia, int hora) {
list<funcionario::Dia>::iterator it;
it = agenda.begin();
while(it != agenda.end() && (*it).d <= dia) {
if((*it).d == dia && (*it).h == hora) {
agenda.erase(it);
return;
}
++it;
}
}
I get this compiling error:
Funcionario.cpp: In constructor ‘funcionario::funcionario()’:
Funcionario.cpp:5: error: cannot convert ‘std::list<funcionario::Dia, std::allocator<funcionario::Dia> >’ to ‘int’ in assignment
Funcionario.cpp: In member function ‘void funcionario::eliminar(int, int)’:
Funcionario.cpp:9: error: request for member ‘begin’ in ‘((funcionario*)this)->funcionario::agenda’, which is of non-class type ‘int’
Funcionario.cpp:10: error: request for member ‘begin’ in ‘((funcionario*)this)->funcionario::agenda’, which is of non-class type ‘int’
Funcionario.cpp:11: error: request for member ‘end’ in ‘((funcionario*)this)->funcionario::agenda’, which is of non-class type ‘int’
I don't know what I'm doing wrong.
Not sure what you're trying to achieve, but the code just needs to be fleshed out a bit with complete function definitions. I got this to compile:
#include <list>
class myClass
{
public:
myClass();
struct myStruct {
int myInfo;
};
void something();
void doSomething(myStruct & ms);
private:
std::list<myStruct> myList;
};
myClass::myClass(){
myList = list<myStruct> ();
}
void myClass::something() {
std::list<myStruct>::iterator it;
it = myList.begin();
while(it != myList.end()) {
doSomething(*it);
++it;
}
}
Incidentally (or maybe directly relevant, not sure) - the copy-initialization of myList in myClass() is unnecessary, as others have stated. The list<> default constructor will do the right thing, and more efficiently.
This seems to be working on my computer, so may it be a compiler problem? Try with another compiler and tell us if it worked
The initialization you're looking for is analogous to Initializing map and set class member variables to empty in C++? - but actually you'll get an empty list automatically (i.e. by the std::list default constructor).
--Edited to reflect your posting of the original code--
H is not declared anywhere.
and is not a valid C++ keyword or token. Use &&.
Use the local header include form of : #include "myClass.hpp"
Related
#include <iostream>
#include <set>
struct ContainerOfA;
struct StructA
{
StructA(ContainerOfA* ptr) : m_b_ptr(ptr)
{}
void CleanMe()
{
m_b_ptr->RemoveStructA(this);
delete this;
}
ContainerOfA* m_b_ptr;
};
struct ContainerOfA
{
void RemoveStructA(StructA *a_ptr)
{
m_set_a.erase(a_ptr);
}
void RemoveAllStructA()
{
for (auto &iter : m_set_a) {
delete iter;
}
}
std::set<StructA*> m_set_a;
};
int main()
{
return 0;
}
g++ (GCC) 10.2.1 20210130
test_me.cpp: In member function ‘void StructA::CleanMe()’:
test_me.cpp:13:12: error: invalid use of incomplete type ‘struct ContainerOfA’
13 | m_b_ptr->RemoveStructA(this);
| ^~
test_me.cpp:4:8: note: forward declaration of ‘struct ContainerOfA’
4 | struct ContainerOfA;
| ^~~~~~~~~~~~
I ran into a circular dependency issue and the sample example is shown above.
Question> Is there a way that I can make it work?
Thank you
Just move the problematic code to a point where the class is defined.
struct StructA
{
// ...
void CleanMe();
// ...
};
struct ContainerOfA
{
// ...
};
inline StructA::CleanMe()
{
m_b_ptr->RemoveA(this);
}
By the way, that's a real code smell having an object know what container it's part of. You should try to architect it so that's not necessary.
Hi I am making a simple stack class in C++ and am new to C++. I am having a few errors that I cannot figure out what they mean. Some help would be greatly appreciated! Here is my code:
Stack.h
#ifndef SStack
#define SStack
#include <cstdlib>
#include <string>
class SStack
{
public:
// Constructor
SStack( int cap);
// Copy Constructor
SStack( const SStack& s );
~SStack( );
void push ( const std::string& s);
std::string& pop ();
std::string& top () const;
bool IsEmpty () const;
int size() const;
int getCapacity() const;
// NONMEMBER FUNCTIONS for the bag class
// Precondition: s1.size( ) + s2.size( ) <= s1.Capacity.
// Postcondition: The stack returned is the union of s1 and s2.
SStack operator +(const SStack& s2);
private:
int Capacity; // Capacity is the maximum number of items that a stack can hold
std::string *DynamicStack;
int used; // How many items are stored in the stack
};
#endif
Stack.cpp
#include "SStack.h"
#include <string>
#include <cstdlib>
#include <iostream>
using namespace std;
class SStack
{
public:
void SStack(int cap){
DyanmicStack = new string[cap];
Capacity = cap;
used = -1;
}
void SStack(const SStack& s){
DyanmicStack = new string[cap];
}
~SStack( ){
delete(DynamicStack);
}
void push(const string& s){
DynamicStack[used] = s;
used++;
}
string& pop(){
if(used==-1){
cout << "Error stack is empty";
return " ";
}
else{
used--;
return DynamicStack[used+1];
}
}
string& top () const{
if(used==-1){
cout << "Error stack is empty";
return " ";
}
else{
return DynamicStack[used];
}
}
bool isEmpty(){
return (used==-1);
}
int size(){
return (used+1);
}
int getCapacity(){
return Capacity;
}
private:
int Capacity; //How much the stack can hold
string* DynamicStack;
int used; //objects in the stack
};
And here are the errors:
SStack.h:11: error: expected unqualified-id before ‘int’
SStack.h:11: error: expected `)' before ‘int’
SStack.h:13: error: expected unqualified-id before ‘const’
SStack.h:13: error: expected `)' before ‘const’
SStack.h:14: error: expected class-name before ‘(’ token
SStack.h:25: error: ISO C++ forbids declaration of ‘operator+’ with no type
SStack.h:25: error: ISO C++ forbids declaration of ‘s2’ with no type
SStack.h:8: error: an anonymous union cannot have function members
SStack.h:31: error: abstract declarator ‘<anonymous class>’ used as declaration
SStack.cpp:11: error: expected unqualified-id before ‘int’
SStack.cpp:11: error: expected `)' before ‘int’
SStack.cpp:17: error: expected unqualified-id before ‘const’
SStack.cpp:17: error: expected `)' before ‘const’
SStack.cpp:21: error: expected class-name before ‘(’ token
SStack.cpp: In member function ‘std::string&<anonymous class>::pop()’:
SStack.cpp:33: error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘const char*’
SStack.cpp: In member function ‘std::string&<anonymous class>::top() const’:
SStack.cpp:44: error: invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘const char*’
SStack.cpp: At global scope:
SStack.cpp:8: error: an anonymous union cannot have function members
SStack.cpp:70: error: abstract declarator ‘<anonymous class>’ used as declaration
Your include guard has the same name as your class. Remember that the preprocessor is a very simplistic search/replace feature.
#define SStack
class SStack
{
public:
// Constructor
SStack( int cap);
becomes:
#define SStack
class
{
public:
// Constructor
( int cap);
One pattern is to name it the same as your header's filename, such as STACK_H.
First of all, as was already noted, the header guard is broken.
Now, onto the actual problems:
You have misunderstood how class definition works. Your header is largely correct, what is wrong is your .cpp file. You are redefining class that you already have defined inside the header file. The proper way to provide implementation of member function is this
void SStack::SStack(const SStack& s){
DyanmicStack = new string[cap];
} or in for clearer example:
void SStack::push(const string& s){
DynamicStack[used] = s;
used++;
}.
Basically, you have to prepend the classes's name before the function name.
Also, just by copy pasting this I've noticed typo in your code (see if you can spot it ;-) ), and I would recommend rethinking the design, even if it is just an exercise.
I realized the class Pila(stack) some times ago, this is my solution:
(sorry but I'm new.. so I don't know how to indent the code here)
file: pila.h
//nodo is the type of elements that class pila contains.
struct nodo
{
int dato;
nodo* precedente;
};
class pila
{
private:
nodo* ultimo;
public:
pila();
void push(int numero);
int pop();
};
file: pila.cpp
#include <iostream>
#include"pila.h"
using namespace std;
pila::pila()
{
ultimo=NULL; // punta all'ultimo nodo inserito
}
void pila::push(int numero)
{
nodo* nuovo;
nuovo=new struct nodo;
nuovo->dato=numero;
if(ultimo==NULL)
{
nuovo->precedente=NULL;
ultimo=nuovo;
}
else
{
nuovo->precedente=ultimo;
ultimo=nuovo;
}
}
int pila::pop()
{
if (ultimo==NULL)
{
return 0;
}
else
{
int prelevato=ultimo->dato;
ultimo=ultimo->precedente;
return prelevato;
}
}
I've encountered these two error when trying to compile..
anyone knows whats wrong ?
Was thinking maybe I #include the wrong header file ?
the sample of the codes and error as per following:
Error:
Square.cpp:8: error: redefinition of ‘Square::Square(bool, Point*, std::string, int)’
Square.h:21: error: ‘Square::Square(bool, Point*, std::string, int)’ previously defined here
Square.cpp: In member function ‘Point Square::getCoord()’:
Square.cpp:22: error: expected primary-expression before ‘]’ token
Square.cpp: In member function ‘void Square::setCoord(Point*)’:
Square.cpp:32: error: expected primary-expression before ‘]’ token
Square.cpp:32: error: expected primary-expression before ‘]’ token
cpp file
#include "Square.h"`
#include <cmath>
using namespace std;
Square::Square(bool containsWarpSpace, Point coord[], string shapeName, int vertPoint):ShapeTwoD(shapeName, containsWarpSpace) {
vertPoint = vertPoint;
coord[] = coord[];
}
int Square::getVertPoint()
{
return vertPoint;
}
Point Square::getCoord()
{
return coord[];
}
void Square::setVertPoint(int verticleP)
{
vertPoint = verticleP;
}
void Square::setCoord(Point coord[])
{
coord[] = coord[];
}
header:
#include "ShapeTwoD.h"
class Square : public ShapeTwoD
{
private:
int vertPoint;
Point coord[];
public:
//Accessor
int getVertPoint();
Point getCoord();
//Mutator
void setVertPoint(int vertP);
void setCoord(Point coord[]);
//virtual member
virtual double computeArea(Point x, Point y);
Square(bool containsWarpSpace, Point coord[], std::string shapeName = "Square", int vertPoint = 4):ShapeTwoD(shapeName, containsWarpSpace){}
};
You are defining the constructor twice, once in the header and once in the implementation file. In the header, you just need to declare it like this:
Square(bool containsWarpSpace,
Point coord[],
std::string shapeName = "Square",
int vertPoint = 4);
You also need to fix the handling of coord, maybe something like changing coord to
Point* coord;
and use
Point* Square::getCoord()
{
return coord;
}
and
this->coord = coord;
in the constructor and setCoord().
Please note that your way of handling coord seems strange and dangerous to me, but without further information about what you are actually trying to do it's hard to give specific advise. Generally, consider using the standard containers over manual memory/array management.
The compiler clearly tells you the problem:
You defined the constructor twice once in header file and once in cpp file.
Also, What exactly do you intend to do with:
coord[] = coord[];
You should understand each and every statement of code that you write. Think about, What do you intend this statement to do? & then match it to the language grammar that you learnt.
Source File:
Square::Square(bool containsWarpSpace, Point coord[],
string shapeName, int vertPoint)
:ShapeTwoD(shapeName, containsWarpSpace)
{
vertPoint = vertPoint;
coord[] = coord[];
}
Header File:
Square(bool containsWarpSpace, Point coord[],
std::string shapeName = "Square", int vertPoint = 4)
:ShapeTwoD(shapeName, containsWarpSpace)
{}
Looks like two different version of the same function.
The one in the header file calls the base class constructor but does not have any code in the body of the constructor.
I am facing an error in one of my projects which I have replicated using a standalone program. I did see several posts pertinent to this, but could not figure out my problem. I am getting the following error with this code : "error: expected constructor, destructor, or type conversion before '&' token"
#include <iostream>
#include <boost/shared_ptr.hpp>
using namespace std;
class X
{
private:
int _x;
public:
X(int x) : _x(x) {};
};
class Y
{
private:
typedef boost::shared_ptr<X> X_ptr;
public:
X_ptr& func1();
};
X_ptr& Y::func1()
{
X_ptr p(new X(8));
return p;
};
int main()
{
return 0;
}
Can someon help me with in resolving this error?
There are two problems. First, you forgot to qualify the type name X_ptr:
Y::X_ptr& Y::func1()
// ^^^ ^
// BUT REMOVE THIS!
Second, notice that you are returning a reference to a local variable. Attempting to dereference the value returned by func1() will give you undefined behavior.
Just change the prototype of your function this way:
Y::X_ptr Y::func1()
// ^^^^^
// Returning the smart pointer by value now
{
X_ptr p(new X(8));
return p;
}
I am trying to implement the a map from the C++ STL as follows:
#include <string>
#include <iostream>
#include <map>
using namespace std;
#include "assembler.h"
// This Class makes use of the Map Template from the Standart Template Library
// All addresses are stored as numerical (Dec) integers
SymbolTable::SymbolTable() { // Constructor
map <string, int> symbolTable;
int address = 0;
}
void SymbolTable::addEntry(string symbol, int address) {
symbolTable[symbol] = address;
address++;
}
// Returns true if symbolTable already contains symbol
bool SymbolTable::contains(string symbol) {
if (symbolTable.find(symbol) == symbolTable.end()) { return true; }
else { return false; }
}
int SymbolTable::getAddress(string symbol) {
return symbolTable[symbol];
}
I try to compile this with
c++ *.cpp -0 assembler.out
and I get the following error message:
symboltable.cpp:57:9: error: no viable conversion from 'mapped_type' (aka 'std::basic_string<char>') to 'int'
return symbolTable[symbol];
^~~~~~~~~~~~~~~~~~~
1 error generated.
I have searched for this error online and all I get is bug reports relating to the STL and I cannot figure out if those reports are the same problem I am having and if so how to get around it. Am I doing something wrong?
I have tried (probably stupidly) to typecast the offending line as
return (int) symbolTable[symbol];
Thank you for any help.
My header file declares the class as:
class SymbolTable {
public:
SymbolTable();
void addEntry(string, int);
bool contains(string);
int getAddress(string);
private:
map <string, string> symbolTable;
int address;
};
This:
SymbolTable::SymbolTable() { // Constructor
map <string, int> symbolTable;
^
^
is a function-local variable, not a member variable. It is not the same as the symbolTable that you're accessing in e.g. getAddress, which presumably is a member variable. You haven't shown the class body, but my guess is that it's defined differently.