Why am I getting a "declaration is incompatible with (x)"? - c++

I'm creating a class called person right now in separate header and cpp files.
And for one of the functions I'm getting this error:
declaration is incompatible with "Person::stat Person::getStat()" (declared at line 26 of "C:...")
(Not the exact directory but you get the idea)
Here is the code in the header file:
#pragma once
#include <string>
#include <iostream>
class Person
{
public:
struct stat {
int str;
int end;
int dex;
int intel;
};
Person();
~Person();
//properties
stat getStat();
};
Here is the code in the cpp file:
#include "pch.h"
#include "Person.h"
#include <string>
#include <iostream>
Person::Person()
:age(12), height(0)
{
}
Person::~Person()
{
}
struct stat Person::getStat() {
}
I'm getting the error with the getStat() function. I've tried including the string and iostream headers in both file and also only in the header file since a similar post suggested it. Both didn't solve my problem however.

Should be
Person::stat Person::getStat() {
}
Your version declares a new struct stat which isn't the same as Person::stat.

struct stat Person::getStat() is a method that returns a stat that belongs to the global namespace, not to Person:
Person::stat Person::getStat()
Note that there is no struct here (to avoid declaring one). In C++, we don't use struct after the type has been declared.

Related

How to resolve a C++ Error: Redefinition of 'class'

I am new to C++ programming and have a compiler error that I can't figure out. Any help would be appreciated.
Here is the build log:
C:\Dev\MemberTest\Entity.cpp|6|error: redefinition of 'class Entity::Entity'|
C:\Dev\MemberTest\Entity.h|6|error: previous definition of 'class Entity::Entity'|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
The program has Main.cpp, Entity.h and Entity.cpp (I was just tinkering with how to implement headers and source files).
#include <iostream>
#include "Entity.h"
int main()
{
Entity::Entity Person("Grant", true); //Create person and set membership
std::cout << Person.getName() << " is a member: " << Person.getMembership() << std::endl;
return 0;
}
#ifndef ENTITY_H_INCLUDED
#define ENTITY_H_INCLUDED
namespace Entity
{
class Entity
{
private:
std::string name;
bool member;
public: //Get, set, constructor calls for a bool and string.
Entity(std::string y, bool x);
bool getMembership();
std::string getName();
void setMembership(bool x);
};
}
#endif // ENTITY_H_INCLUDED
#include <string>
#include "Entity.h"
namespace Entity
{
class Entity
{
private:
std::string name;
bool membership;
public:
Entity(std::string y, bool x):name(y),membership(x){}
bool getMembership(){return this->membership;};
std::string getName(){return this->name;};
void setMembership(bool x){this->membership=x;};
};
}
I've looked around for a solution and found questions like this: error: redefinition of class but the solutions I'm seeing aren't relevant to my program because I'm already using #ifndef.
Since I'm not sure what other info might be needed here goes: All three files are in the same folder and there aren't other source or header files in that folder. Oddly enough if I comment out the #include "Entity.h" in the Entity.cpp file and reference the source in Main.cpp instead of Entity.h it compiles and runs fine. I'm coding on Code::Blocks and with the GCC Compiler. Thanks again for any help.
The implementation file (Entity.cpp) should not contain the class definition again. Instead, you write non-inline definitions ("out of class"):
#include <string>
#include "Entity.h"
namespace Entity
{
Entity::Entity(std::string y, bool x) : name(y), membership(x) {}
bool Entity::getMembership() { return membership; }
std::string Entity::getName() { return name; }
void Entity::setMembership(bool x) { membership = x; }
}
Also note that your Entity.h header depends on std::string which requires the #include <string> header there, not just in the implementation file (Entity.cpp). There is no need to use this-> here nor some of the semicolons (;).
Oddly enough if I comment out the #include "Entity.h" in the Entity.cpp file and reference the source in Main.cpp instead of Entity.h it compiles and runs fine
That is because you can define functions inline in the class (instead of putting them in the implementation file). What you did is implement all of them in the class definition, and therefore you don't need an implementation file anymore.
In other words, your Entity.cpp looked like a header file with a full implementation of the class, although you called it .cpp rather than .h. Thus if you include that file, it would work.

C++ - error: class has not been declared/out of scope

So I have two classes - Dvd and DvdGroup. DvdGroup basically manages an array of dvds and provide manipulative member functions for that class. The problem is whenever I try to compile DvdGroup.cc using the command 'g++ -c Dvd.Group.cc', I get a bunch of errors all related to not having 'Dvd' declared and I'm not sure why.
Here are some errors below:
DvdGroup.h:14:12: error: ‘Dvd’ has not been declared void add(Dvd*);
DvdGroup.h:18:3: error: ‘Dvd’ does not name a type Dvd* dvdCollection[MAX_DVDS];
DvdGroup.cc: In copy constructor ‘DvdGroup::DvdGroup(DvdGroup&)’:
DvdGroup.cc:15:6: error: ‘Dvd’ was not declared in this scope for(Dvd d: dvds){
I feel like I'm missing something and they could all be fixed by one solution because they all involve having the Dvd class undeclared but I can't seem to figure out what. I was wondering if anyone could tell me what I'm doing wrong? I would really appreciate any help with fixing this.
DvdGroup.cc:
#include <iostream>
using namespace std;
#include "DvdGroup.h"
DvdGroup::DvdGroup(int n){
numDvds = n;
}
DvdGroup::DvdGroup(DvdGroup& dvds){
numDvds = dvds.numDvds;
for(Dvd d: dvds){
Dvd newDvd = Dvd;
}
}
DvdGroup::~DvdGroup(){
//code
}
void DvdGroup::add(Dvd* d){
//code
}
DvdGroup.h:
#ifndef DVDGROUP_H
#define DVDGROUP_H
#define MAX_DVDS 15
#include <string>
using namespace std;
class DvdGroup
{
public:
DvdGroup(int);
DvdGroup(DvdGroup&);
~DvdGroup();
void add(Dvd*);
private:
Dvd* dvdCollection[MAX_DVDS];
int numDvds;
};
#endif
Don't know if the Dvd header file is needed, but here:
Dvd.h:
#ifndef DVD_H
#define DVD_H
#define MAX_DVDS 15
#include <string>
class Dvd{
public:
Dvd(string, int);
void set(string, int);
Dvd(Dvd&);
int getYear();
~Dvd();
void print();
private:
string title;
int year;
};
#endif
What you need to do is to provide Dvd class definition for DvdGroup class. It is needed to know what type of symbol is this. Solution for your problem should be addition of:
#include "Dvd.h"
line to DvdGroup.h file.

Order of header file inclusions and dependencies

I'm just trying to test splitting code into multiple files.
I have:
//testMultiple.cpp
#include <string>
#include <iostream>
#include "testInclude.cpp"
int main(){
std::cout << "hi";
}
and
//testInclude.cpp
class testClass{
public:
string x;
};
This is giving testInclude.cpp:3:9: error: ‘string’ does not name a type
I thought since it was including before it included the testInclude.cpp, string would be defined for use in testInclude.cpp.
You need to use std::string instead of string.
You're including a cpp file, not a hpp file.
Common practice is to include header (h/hpp) files, not implementation (c/cpp) files.
If you only compile testMultiple.cpp, this should work. If the compiler is compiling testInclude.cpp separately, it will not see the `#include
Try renaming testInclude.cpp to testInclude.hpp and ensure it is not being compiled.
Here's an example:
///// testInclude.h
#include <vector>
class testClass{
public:
std::vector<int> x; // vector is in std namespace
};
///// testMultiple.cpp
// #include <vector> - gets this through testInclude.h
#include "testInclude.h"
int main(){
}
Use
class testClass{
public:
std::string x;
};

Using class instead of struct and constructor issues

I am trying to move from using structs to using classes, and I have a few questions with my - not fully complete, but enough to illustrate my queries - code (thank you in advance for clarifying these):
I am having problems with creating a constructor that takes in arguments, specifically the line in the header file that I have currently left as neighborAtt(int neighbor_id, int att_1, int att_2);.
When using neighborAtt as a struct, I could do it easily as neighborAttributes currentNode(neighborID, att1, att2);. What is the class-equivalent?
In the .cpp file, I know that I need to define the constructor as neighborAtt::neighborAtt().
Do I need to this with the functions (i.e. include neighborAtt::) or is what I've done accurate?
This is my header file:
#if !def connectivity_H
#define connectivity_H
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <sstream>
#include <fstream>
class listAtt;
class vecListAtt;
class neighborAtt //contains the neighbour and associated attributes of a node
{
public:
neighborAtt();
neighborAtt(int neighbor_id, int att_1, int att_2);
vecListAtt connFrFile(int file_ext);
vecListAtt makeList(std::vector<std::list<neighborAtt>> nodeAndInfo, int nodeID, neighborAtt neighAndAtt);
neighborAtt getAtt(std::string currentLine);
private:
int neighborID;
int attribute1;
int attribute2;
};
typedef std::list<neighborAtt> listAtt;
typedef std::vector<listAtt> vecListAtt;
#endif
and the .cpp file:
#include "stdafx.h"
#include "connectivity.h"
neighborAtt::neighborAtt(): neighborID(0), attribute1(0), attribute2(0) {}
//neighborAtt::neighborAtt constructor with arguments
vecListAtt connFrFile(int file_ext)
{
//code
}
neighborAtt getAtt(std::string line)
{
//code
}
For the second constructor (one with the arguments) you do just the same as for one without them. Or did I get the question wrong? It'd be like:
neighborAtt::neighborAtt(int neighbor_id, int att_1, int att_2)
: neighborID(neighbor_id),
attribute1(att_1),
attribute2(att_2)
{
}
And for the methods you must go the same way:
vecListAtt neighborAtt::connFrFile(int file_ext)
{
//code
}

Redefinition of class

I got three .cpp files and two header files.
But when i compile them, meaning the Point.cpp, Data.cpp and main.cpp, it will say
Data.h:6:7 redefinition of Data at 'Data.h'
Data.h:6:7 previously definition of 'class Data'
Below is my Data.h(previously known as 2.h at above)
#include <iostream>
#include <string>
using namespace std;
class Data
{
private:
string sType;
public:
Data();
Data(string);
void setSType(string);
string getSType();
};
Below is my data.cpp
#include "Data.h"
Data::Data()
{
sType = "";
}
Data::Data(string s)
{
sType = s;
}
void Data::setSType(string ss)
{
sType = ss;
}
string Data::getSType()
{
return sType;
}
Below is my PointD.h (previously known as 3.h)
#include <iostream>
#include <string>
#include "Data.h"
using namespace std;
class PointD
{
private:
int x
Data data1;
public:
PointD();
PointD(int,Data);
void setX(int);
void setData(Data);
int getX();
Data getData();
};
Below is my PointD.cpp
#include "PointD.h"
PointD::PointD()
{
x = 0;
}
PointD::PointD(int xOrdinate,Data dd)
{
x = xOrdinate;
data1 = dd;
}
void PointD::setXordinate(int Xordinate)
{
x = Xordinate;
}
void PointD::setData(Data dd)
{
data1 = dd;
};
int PointD::getXordinate()
{
return x;
}
Data PointD::getData()
{
return data1;
}
This is my main.cpp
#include <iostream>
#include <string>
#include "Data.h"
#include "PointD.h"
using namespace std;
int main()
{
const int MAX_NUM = 20;
Data ldata[MAX_NUM];
PointD pointd[MAX_NUM];
//more codes..
}
But when i compile them, meaning the Point.cpp, Data.cpp and main.cpp, it will say
Data.h:6:7 redefinition of Data at 'Data.h'
Data.h:6:7 previously definition of 'class Data'
Can anybody let me know whats actually went wrong here..
You need to use include guards, or the easiest:
#pragma once
in your header files
See Purpose of Header guards for more background
Idea: 1.hpp
#ifndef HEADER_GUARD_H1_HPP__
#define HEADER_GUARD_H1_HPP__
// proceed to declare ClassOne
#endif // HEADER_GUARD_H1_HPP__
In each of your header files write:
#ifndef MYHEADERNAME_H
#define MYHEADERNAME_H
code goes here....
#endif
Its better like this:
#ifndef DATA_H /* Added */
#define DATA_H /* Added */
#include <iostream>
#include <string>
// using namespace std; /* Removed */
class Data
{
private:
std::string sType;
public:
Data();
Data( std::string const& ); // Prevent copy of string object.
void setSType( std::string& ); // Prevent copy of string object.
std::string const& getSType() const; // prevent copy on return
std::string& getSType(); // prevent copy on return
};
#endif /* DATA_H */
The big fix is adding ifndef,define,endif. The #include directive works as if copying and pasting the .h to that line. In your case the include from main.cpp are:
main.cpp
-> Data.h (1)
-> Point.h
-> Data.h (2)
At (2), Data.h has already been `pasted' into main.cpp at (1). The class declaration of Data, i.e. "class Data{ .... };" , appears twice. This is an error.
Adding include guards to the top and bottom of every .h are standard practice to avoid this problem. Don't think about it. Just do it.
Another change I'd suggest is to remove any "using namespace ..." lines from any .h . This breaks the purpose of namespaces, which is to place names into separate groups so that they are not ambiguous in cases where someone else wants an object or function with the same name. This is not an error in your program, but is an error waiting to happen.
For example, if we have:
xstring.h:
namespace xnames
{
class string
{
...
};
}
Foo.h
#include <xstring>
using namespace xnames;
...
test.cxx:
#include "Foo.h"
#include "Data.h" // Breaks at: Data( string ); -- std::string or xnames::string?
...
void test()
{
string x; // Breaks. // std::string or xnames::string?
}
Here the compiler no longer knows whether you mean xnames::string or std::string. This fails in test.cxx, which is fixable by being more specific:
void test()
{
std::string x;
}
However, this compilation still now breaks in Data.h. Therefore, if you provide that header file to someone, there will be cases when it is incompatible with their code and only fixable by changing your header files and removing the "using namespace ...;" lines.
Again, this is just good coding style. Don't think about it. Just do it.
Also, in my version of Data.h, I've changed the method parameters and return types to be references (with the &). This prevents the object and all of its state from being copied. Some clever-clogs will point our that the string class's is implementation prevents this by being copy-on-write. Maybe so, but in general, use references when passing or returning objects. It just better coding style. Get in the habit of doing it.