I have the following structure declared in main (NEVERMIND THE MEMBERS!) :
struct args
{
std::vector<string> names;
std::vector<std::shared_ptr<RegularExpression>>vreg;
std::vector<string> stopFile;
std::vector<string> groundTruth;
int debug;
};
and I have a classe Verification that takes args as a constructor parameter
#ifndef VERIFICATION_H
#define VERIFICATION_H
class Verification
{
public:
Verification(std::string, std::vector<double>,double,args);
private:
args _A;
}
#endif // VERIFICATION_H
Now in main:
struct args
{
std::vector<string> names;
std::vector<std::shared_ptr<RegularExpression>>vreg;
std::vector<string> stopFile;
std::vector<string> groundTruth;
int debug;
};
int main()
{
Verification v("res.cr",gt, 0.75,A);
return 0;
}
I have the following compile errors :
Verification.h|33|error: 'args' does not name a type| (this error is for the private member in the class _A)
main.cpp|153|error: no matching function for call to 'Verification::Verification(const char [7], std::vector&, double, args&)'|
Verification.h|24|error: 'args' has not been declared|(this error is the constructor)
How can I use the structure declared in main as a constructor parameter in class verification?
Thank you.
The structure must be defined in a way that it is visible to the Verification class translation unit. I suggest you move the struct to its own header file, and #include that in your main file and in Verification.h.
The first error is that when compiling class Verification the compiler must see struct args first. It doesn't know that you are gonig to define struct args later.
Simple fix would be to move the definition of struct args into Verification.h.
Fix that and you'll still have other errors though (most obviously that there's no definition for A), but we can deal with those when you get to them.
Your second error is due to the fact that a string literal is a const char[], not a std::string- you need to create a string before passing it to a function expecting a string.
Also, gt and A need to be defined before this call.
Related
I have a class called scratch and have used scratch.h to declare it.
Now I have another class called scratch2 under scratch2.h and want to create an object of scratch as a shared pointer.
This is the syntax I used inside scratch2 class declartion:
std::shared_ptr<scratch> newObject(new scratch());
But I am getting this error: Error: Expected type specifier
So I tried this instead:
std::shared_ptr<scratch> newObject2 = std::make_shared<scratch>();
which works fine. Can anyone please tell me why the first one isn't working?
My scratch.h code:
#ifndef _SCRATCH_
#define _SCRATCH_
#include <iostream>
class scratch {
private:
int _a;
float _b;
std::string _s;
public:
scratch();
scratch(int a, float b, std::string n);
~scratch();
};
#endif
and my scratch2.h:
#ifndef _SCRATCH_2_
#define _SCRATCH_2_
#include "scratch.h"
#include <memory>
class scratch2 {
std::shared_ptr<scratch> newObject(new scratch()); // Expected a type specifier error occurs here
std::shared_ptr<scratch> newObject2 = std::make_shared<scratch>(); // works fine here
};
#endif
Because in the context of declaring class members:
std::shared_ptr<scratch> newObject(new scratch());
This initially looks to the compiler as a class method declaration. C++'s syntax is very complicated. You can look at the entire declaration and understand what it's trying to do, but the compiler is parsing keywords one keyword at a time, and sees this:
type name( ...
inside a class declaration, and this starts to look like a class method declaration, and that's what the compiler tried to parse, and failed.
The formal specification of the C++ language spills a lot of ink on the subject of how things should be declared, mindful of the current state of compiler technology.
You need to work with the compiler, and use an alternate syntax that's unambiguous:
std::shared_ptr<scratch> newObject = std::shared_ptr<scratch>(new scratch());
Verified with gcc 5.3
Inside of a class definition, there are only two ways you're allowed to initialize your members. You can use = and you can use {}. You are not allowed to use ():
struct foo {
int x = 4; // OK
int y{7}; // OK
int z(12); // error
};
Admittedly, the compiler error in this case is extremely unhelpful.
It is probably some stupid syntax mistake, i have the following class written in h file
#include "IGenticSolverHelper.h"
template <class T>
class GenericGeneticSolver
{
public:
GenericGeneticSolver(IGenticSolverHelper<T>& helper, int generationSize) : mSolverHelper(helper)
{
mSolverHelper.GenerateFirstGeneration(0, generationSize, currentGeneration);
}
private :
vector<T> currentGeneration;
IGenticSolverHelper<T>& mSolverHelper;
};
And then the following code :
#include "IGenticSolverHelper.h"
#include "GenericGeneticSolver.h"
class HelperImpl : IGenticSolverHelper<int>
{
public:
void GenerateFirstGeneration(const int seed,const int generationSize, vector<int>& firstGeneration)
{
}
void Crossover(const int& father,const int& mother, int& son)
{
}
void Mutate(const int& orignal, int& mutated)
{
}
float Cost(int& solution)
{
}
};
int main()
{
int a =5;
GenericGeneticSolver<int> mySolver(HelperImpl,a);
}
And i get the following error when i compile :
error C2061: syntax error : identifier 'a'
if i will change the line to :
GenericGeneticSolver<int> mySolver(HelperImpl);
it will compile, though the constructor expect 2 arguments, and will get the following warning :
warning C4930: 'GenericGeneticSolver<T> mySolver(HelperImpl)': prototyped function not called (was a variable definition intended?)
And to add to the oddness, when i put a break point on this line, he won't stop there.
What am i doing wrong, i just trying to create an instance of GenericGeneticSolver
Take a look at this line:
GenericGeneticSolver<int> mySolver(HelperImpl,a);
The compiler is confused about what you're trying to do here because HelperImpl is the name of a type, while a is the name of an object. The compiler thinks what you're doing is trying to prototype a function named mySolver that takes in a parameter of type HelperImpl and a parameter of type a, but then gets stuck because it doesn't know of any types named a.
If you remove a, you get this:
GenericGeneticSolver<int> mySolver(HelperImpl);
This is a perfectly legal prototype of a function called mySolver that takes an argument of type HelperImpl and returns a GenericGeneticSolver<int>. The warning you're getting is the compiler telling you that you might not have meant to make this a prototype, since it somewhat looks like an instantiation of a variable named mySolver but isn't.
Since I assume that you're trying to instantiate an object of type GenericGeneticSolver<int> here, you probably want to instantiate a HelperImpl and then pass that object into the constructor, like this:
HelperImpl hi;
GenericGeneticSolver<int> mySolver(hi, a);
Hope this helps!
I have a constructor for a class that takes in a bool, a pointer to an array, and string.
TheConstructor(bool theBool=true, int *theArray=0, std::string message="0");
Is this the correct way to write it in the header file? My program isn't compiling right now because of a "undefined reference to "the constructor" and to other member functions".
What could be causing this also? I checked and in main.cpp I #included "Class.h" and defined every memberwise function that needed to be defined that was stated in "Class.h" I wrote in "Class.cpp"
I hope you didn't name your class TheConstructor :) If you have class C you can declare its constructor almost as you did - you forgot to put the name of the bool argument:
C.h:
#include <string>
class C
{
public:
C(bool b = 0, int *theArray = 0, std::string message = "0");
};
C.cpp:
#include "C.h"
C::C(bool b, int *theArray, std::string message)
{
}
The first parameter's name is not specified, but that probably wouldn't cause the error you're encountering:
TheConstructor(bool=0, int *theArray=0, std::string message="0");
You probably want to do something like this:
TheConstructor(bool flag=0, int *theArray=0, std::string message="0");
However, without seeing the definition, there is not much else I can say about it. It's difficult to predict what else could be wrong by simply looking at the declaration.
Yet another Scrabble project question... This is a simple one.
It seems I am having trouble getting my global constants recognized:
My board.h:
http://pastebin.com/7a5Uyvb8
Errors returned:
1>C:\Users\Francisco\Documents\FEUP\1A2S\PROG\projecto3\projecto3\Board.h(34): error: variable "TOTAL_ROWS" is not a type name
1> vector< vector<Cell> > _matrix(TOTAL_ROWS , vector<Cell>(TOTAL_COLUMNS));
1>
1>main.cpp
1>compilation aborted for .\Game.cpp (code 2)
1>Board.cpp
1>.\Board.h(34): error: variable "TOTAL_ROWS" is not a type name
1> vector< vector<Cell> > _matrix(TOTAL_ROWS , vector<Cell>(TOTAL_COLUMNS));
1> ^
1>
Why does this happen? Why is the compiler expecting types?
Thanks for your time!
EDIT:
Disregard my previous edit...
This is my default constructor:
Board::Board()
{
_matrix(TOTAL_ROWS, vector(TOTAL_COLUMNS));
}
I get the following error.
1>.\Board.cpp(16): error: call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type
1> _matrix(TOTAL_ROWS, vector<Cell>(TOTAL_COLUMNS));
1> ^
Why does this happen?
I managed to solve all the problems with my file. I used
Board::Board() :
_matrix(TOTAL_ROWS, vector<Cell>(TOTAL_COLUMNS))
{}
instead. Thanks for all your help!
The way that is written, you are defining a function called _matrix that returns a vector. So TOTAL_ROWS is expected to be a type name, since it is being parsed as a paramter type. I assume what you are trying to do is define a variable called _matrix that is a vector.
What you want to do is leave off the constructor, and initialize the variable inside your constructor. Only constant integral values can be initialized in the body of the class, at least in the current version of the standard.
Leaving off the unimportant parts:
Board() : _matrix(TOTAL_ROWS, vector<Cell>(TOTAL_COLUMNS)) { }
private:
vector< vector<Cell> > _matrix;
Note that this is just an example. Presumably you have an implementation file with an actual body for Board(), and you should put the initialization there rather than directly in the header or you'll get errors. The important thing is that you should not do it when you declare _matrix initially.
For your new question, extern const unsigned int TOTAL_COLUMNS = 15; defines TOTAL_COLUMNS every time Board.h is included by a file. Constant variables at namespace scope have internal linkage by default, so if you leave off the extern you will be okay.
In general, if the variable isn't constant, you take an approach similar to the one for _matrix. You leave off the initialization in the header, and then inside an implemenation file put it back on:
board.h:
extern const int TOTAL_COLUMNS;
board.cpp:
extern const int TOTAL_COLUMNS = 15;
You try to initialize the vector on it's definition, which is not the correct way to do this for object variables, the correct way is this:
extern const unsigned int TOTAL_ROWS = 15;
extern const unsigned int TOTAL_COLUMNS = 15;
class Board
{
public:
Board() : _matrix(TOTAL_ROWS, vector<Cell>(TOTAL_COLUMNS)) {}
private:
vector< vector<Cell> > _matrix;
};
In your header file, I see:
private:
vector< vector<Cell> > _matrix(TOTAL_ROWS , vector<Cell>(TOTAL_COLUMNS));
This seems to be declaring a private member variable, _matrix, and is apparently an effort to call the constructor for _matrix at the same time. You cannot call the constructor in this way.
Remember that your header file may be included in MANY program files.
As a result, headers should not contain execution instructions (certain exceptions exist, such as inline methods and templates). You never know where the header will be included, so you never know where the code in a headerfile will appear.
It is good advice to write your header files so that they are safe to be included anywhere.
If you want to continue this code, I suggest:
The constructor of Board() should construct the member variable explicitly:
Board::Board() :
_matrix(TOTAL_ROWS, .....);
// This will call the matrix constructor ONLY when the Board constructor is called.
{
}
Then the Board constructor should be called, but ONLY in a .cpp file, not in a .h file.
This is my default constructor:
Board::Board() { _matrix(TOTAL_ROWS,
vector(TOTAL_COLUMNS)); }
I get the following error. [ .... ]
You did not follow the examples and syntax provided by #Dennis Zickefoose, #KillianDS, and myself.
Please re-read our answers and study our code.
You can't call a constructor in the header file (or any code for that matter).
I have a the following method definition in my class:
virtual Calc* Compile(
Evaluator* evaluator, ResolvedFunCall* fun_call, string* error);
For some reason, GCC complains that:
error: 'Compile' declared as a 'virtual' field
Any ideas why it would believe Compile to be a field, instead of a method?
I get that error when the first parameter doesn't make sense to it. Check that Evaluator is known as type:
struct A {
virtual void* b(nonsense*, string*);
};
=> error: 'b' declared as a 'virtual' field
struct A {
virtual void* b(string*, nonsense*);
};
=> error: 'nonsense' has not been declared
To find out whether something is a object or function declaration, the compiler sometimes has to scan the whole declaration. Any construct within the declaration that could possibly form a declaration is taken to be a declaration. If not, then any such construct is taken to be an expression. GCC apparently thinks because nonsense is no valid type, it can't be a valid parameter declaration, and thus falls back treating the whole declaration as a field (note that it says in addition error: expected ';' before '(' token ) . Same thing in local scope
int main() {
int a;
// "nonsense * a" not treated as declaration
void f(nonsense*a);
}
=> error: variable or field 'f' declared void
int main() {
// "nonsense * a" treated as parameter declaration
typedef int nonsense;
void f(nonsense*a);
}
=> (compiles successfully)
This happened to me when I declared a virtual function with {} instead of ().
A sample to demonstrate the error:
test.h
class Test{
public:
Test(){}
~Test(){}
//next line is defective, use () instead of {}
virtual int myfunct{int i};//notice brackets here which causes the error
};
test.cpp
#include "test.h"//i omitted include guards for simplicity
int Test::myfunct(int x){
x=5;
return x;
}
main.cpp
#include "test.h"
int main(){
Test test;
return 0;
}