C++: Function call error: identifier "name" is undefined, when already defined? - c++

I'm having problems with several C++ programs simply not wanting to run the functions that are defined clearly in a public class above main. I've looked far and wide for answers, but similar problems are the result of not having a scope resolution operator or something similar. As far as I can tell, everything required to call this function is there.
#include <iostream>
#include <stdlib.h>
#include <Windows.h>
using namespace std;
class Box{
public:
Box();
Box(int x, int y);
Box(int x, int y, char type);
Box(char type);
//Accessor functions:
int GetY();
int GetX();
char GetChar();
//Mutator functions:
void SetCoords(int x, int y);
void SetChar(char x);
//Output function:
void printbox(void);
private:
int ycoord;
int xcoord;
char drawing;
};
int main(int argc, char* argv[])
{
Box();
printbox();
return 0;
};
void Box::printbox(void){
//working code
};
What I get instead is error C3861: 'printbox' identifier not found. What's missing that lets the printbox (and other functions like these) run?

printbox is a method therefore you have to call it on an object of type Box. Like this
Box b;
b.printbox();

Related

2 classes with the same name within namespaces

I have gone back to learning C++ doing some old university courses and I am now currently learning parametric polymorphism as well as creating my own namespaces.
The exercise states that I have to make a namespace called "Federation" which has a class called "Ship" that takes values and one default value that never changes.
inside the federation namespace there is also a "Starfleet" namespace in which we also have a "Ship" class, the only difference is that the default value stated before can be specified by the user.
Here is the code:
Federation.hpp
#include <iostream>
#include <string>
#include <cstring>
namespace Federation
{
namespace Starfleet
{
class Ship
{
public:
Ship(int length, int width, std::string name, short maxWarp);
~Ship();
private:
int _length;
int _width;
std::string _name;
short _maxWarp;
};
};
class Ship
{
public:
Ship(int length, int width, std::string name);
~Ship();
private:
int _length;
int _width;
std::string _name;
}
};
Federation.cpp
#include "Federation.hpp"
using namespac std;
Federation::Starfleet::Ship::Ship(int length, int width, string name, short maxWarp): _length(length), _width(width), _name(name), _maxWarp(maxWarp)
{
cout << "Starfleet Ship Created." << endl;
}
Federation::Starfleet::Ship::~Ship()
{
}
Federation::Ship::Ship(int length, int width, string name, int speed = 1): _length(length), _width(width), _name(name)
{
cout << "Regular Ship Created"
}
Federation::Ship::~Ship()
{
}
main.cpp
#include "Federation.hpp"
int main(int ac, char **av)
{
Federation::Starfleet::Ship mainShip(10, 10, "Starfleet Ship", 20);
Federation::Ship smallShip(5, 5, "Small Ship");
}
When compiling I get this Error: "prototye for Federation::Ship::Ship(int, int, std::__cxx11::string, int) does not match any class in Federation::Ship"
I am totally lost as to what this means, when I look at my functions on my hpp file all of them seem to be correct, so I don't really understand what exactly I'm doing wrong in this case.
This has nothing to do with namespaces. You declare the c'tor with a certain prototype in the header:
Ship(int length, int width, std::string name);
And then randomly add a parameter with a default argument in the implementation file:
Federation::Ship::Ship(int length, int width, string name, int speed = 1)
Argument types are a part of any function or constructor's signature. So you have a declaration and definition mismatch. Declare the extra parameter in the header (along with the default argument).
Ship(int length, int width, string name, int speed = 1);
// and
Federation::Ship::Ship(int length, int width, string name, int speed)

C2061 - Circular dependency

How to avoid circular dependency on these code:
Mechanic.cpp:
#include "stdafx.h"
#include "Characters.h"
#include "Monsters.h"
using namespace characters;
using namespace monsters;
using namespace std;
void character::character_atack(character const cha, monster &monst)
{
if (cha.dexterity + k(20) >= monst.defense)
monst.health = monst.health - cha.strength;
}
int k(int const max)
{
return (rand() % max);
}
void monster::monster_atack(character &cha, monster const monst)
{
if (monst.atack + k(20) >= cha.dexterity)
cha.health = cha.health - monst.damage;
}
Monsters.h:
#include <iostream>
#include <string>
namespace monsters
{
using namespace std;
class monster{
protected:
string name;
public:
int atack;
int damage;
int health;
int defense;
monster(int atk, int dmg, int hp, int def) : atack(atk), damage(dmg),
health(hp), defense(def) {}
~monster();
void monster_atack(character &cha, monster const monst);
};
class greenskins:monster{
greenskins(int atk, int dmg, int hp, int def) : monster(atk, dmg, hp, def) {}
};
}
Characters.h:
#include <iostream>
#include <string>
#include <vector>
namespace characters
{
using namespace std;
class character{
protected:
int level;
int experience;
string name;
public:
int health;
int strength;
int intelligence;
int dexterity;
struct position{
int x;
int y;
}pos;
character(int str, int in, int dex) : strength(str), intelligence(in),
dexterity(dex), level(1), experience(0) {
cout << "What's your name?" << endl;
cin >> name; }
~character();
void info_character();
void character_atack(character const cha, monster &monst);
};
}
The compilator gives me errors like this:
Error 1 error C2061: syntax error : identifier 'monster'
or
Error 9 error C2511: 'void monsters::monster::monster_atack(characters::character &,const monsters::monster)' : overloaded member function not found in 'monsters::monster'
The issue is that character has a function that takes a monster& and monster has a function that takes a character&, but you don't declare the other class in either case. Thankfully, since you just pass the classes as arguments in both places (as opposed to having them be members or something), it is sufficient to forward-declare both classes in both places:
// in character.h
namespace monsters {
class monster; // just fwd-declare
}
namespace characters {
class character {
// as before
};
}
And similar in the other file.
[update] Also, you're just referencing monster inside of class character in the header file, you need to qualify it as monsters::monster.
The first error comes from the following line in Characters.h
void character_atack(character const cha, monster &monst);
You include Characters.h into your .cpp file before you include the Monsters.h and thus the type monster is not yet known. To fix this, change your Characters.h to look like this:
... //includes
namespace monsters {
class monster;
}
namespace characters {
class character {
... //class definition
}
}
The second error is a not matching signature. You are declaring following method:
void monster_atack(character &cha, monster const monst)
but defining
void monster::monster_atack(character &cha, const monster monst)
At least that is what the compiler said.
I would suggest to change the signature to:
void monster_atack(character &cha, const monster& monst)
to prevent needless copy operations. (depending on optimization of course)

C++ inherited functions not being found

I new in C++ and I have difficulty to understand how to get my function with inheritance.
I have a Class that is link to another with inheritance, everything work except:
I cannot reach my superclass function.
Here's my class header : Point.h (I don't include the .cpp):
#ifndef Point_H
#define Point_H
#include <iostream>
class Point{
public:
Point();
void set_values (int , int);
void set_values (int , int , int );
void affichervaleurs();
int getX() const { return x; }
int getY() const { return y; }
private:
int x ;
int y ;
int z ;
};
#endif
Now My other class that try to access the function getX from Point.h :
The header : Carre.h
#ifndef Carre_H
#define Carre_H
#include "Point.h"
class Carre : public Point{
public:
Carre();
//Carre(int a , int b);
//Carre(int a, int b):Point(a,b) {};
//Carre(int a, int b, int c):Point(a, b, c) {};
//const Point &pp;
int Aire (){
};
void affichercar(){
};
};
#endif
Carre.cpp
#include <iostream>
using namespace std;
#include "Carre.h"
#include "Point.h"
Carre::Carre():Point(){
};
//Carre::Carre(int a, int b);
//const &pp;
int Aire (){
return (getX() * getY());
};
void affichercar(){
//cout << "Coordonnees X:" << x << endl;
};
It says that my GetX() is undeclared in my Carre.cpp .
Like I said I'm new in C++
Does someone know what I'm missing to make that code work. ?
Your definition is missing the class scope, which makes it a free function instead of a member.
It should be
int Carre::Aire (){
return getX() * getY();
};
In the .cpp file for Carre, the functions Aire and affichercar are global. Presumably you intended:
int Carre::Aire(){
return (getX() * getY());
};
For example.
Declaring function outside class body requires a class specifier:
int Carre::Aire () {
return (getX() * getY());
};
void Carre::affichercar() {
//...
}
Otherwise
int Aire () {
return (getX() * getY());
};
is just another function in global namespace that can exists simutaneously to Carre::Aire().
This is because you are not implementing the Aire function as being part of the Carre class.
Try changing
int Aire (){
to
int Carre::Aire (){
Also, you already have an implementation of the Aire method in the header file. You should either implement the function inline in the header file, or in the .cpp file, but not both. This also applies to your affichercar method.

Type value mismatch error with vectors

I get the following error message when I try to run my program:
main.cpp|44|error: type/value mismatch at argument 1 in template
parameter list for 'template<class _Tp, class _Alloc> class
std::vector' main.cpp|44|error: expected a type, got '(render)3u'
main.cpp|44|error: template argument 2 is invalid main.cpp|44|error:
invalid type in declaration before ';' token
=== Build finished: 4 errors, 0 warnings (0 minutes, 0 seconds) ===
And here is my code for main leading up to the error causing line:
#include<stdlib.h>
#include<windows.h>
#include<GL/glut.h>
#include<GL/freeglut.h>
#include<iostream>
#include <vector>
#include "include/Block.h"
#include <string>
#include <sstream>
#include "include/TextBlock.h"
#include "include/Enemy.h"
string text;
stringstream ss;
enum render {Normal,SelectRangeText,SelectSText,Enemy,EnemyTypeSelection};
enum render state;
enum type { Foreground, Background, Midground };
enum type selected;
enum types { Blocks, Enemies, Text };
enum types special;
string names[4] = { "grass" , "smallGrassBlock" , "dirt" , "sand" };
void createEnemy(int,int);
void addEnemyWaypoint(int,int);
void addToList(vector<Block> &list,int x,int y);
void placeText(int x,int y);
void initTextures();
GLint GetTexture(string file);
void IdleFunction();
void removeBlock(int x,int y);
int xOffset,yOffset,multiuse = 0;
using namespace std;
string to_string(int number);
void placeBlock(int x,int y);
void drawBitmapText(char *string, float x, float y, float z);
void reshape(int w, int h);
void render(void);
void keyboard(unsigned char c,int x,int y);
void mouse(int button,int state, int x, int y);
void arrows(int key, int x, int y );
std::vector <Block> backBlockList;
std::vector <TextBlock> textBlockList;
std::vector <Block> midBlockList;
std::vector <Block> foreBlockList;
std::vector <Enemy> enemyList;//error occurs here
GLuint textures[1];
unsigned int screenXSize=800;
unsigned int screenYSize=800;
unsigned int selectedBlockType = 1;
int main(int argc, char ** argv)
{
The header for enemy:
#ifndef ENEMY_H
#define ENEMY_H
#include<GL/freeglut.h>
#include <vector>
class Enemy
{
public:
Enemy(int Type );
virtual ~Enemy();
void render(int,int,GLuint);
void addWaypoint(int,int);
protected:
private:
int type;
std::vector <int> X, Y;
int xsize,ysize;
};
#endif // ENEMY_H
And the constructor for enemy:
Enemy::Enemy(int Type)
{
xsize=30;
ysize=30;
type=Type;
}
However it will run corrrectly if I substitute the type of my vector to an int.
When the following line is commented out: std::vector enemyList; it compiles, however if it's there it doesn't
when declaring an Enemy like this
Enemy e(5);
it runs correctly
Updates:
If i change the enemy header, and cpp to something like the following:
CPP:
#include "../include/Enemy.h"
Enemy::Enemy( )
{
}
Enemy::~Enemy()
{
//dtor
}
Header
#ifndef ENEMY_H
#define ENEMY_H
class Enemy
{
public:
Enemy( );
~Enemy();
protected:
private:
};
#endif // ENEMY_H
It still crashes with the same error, this means it must be something in main
FIX:
For some reason when I declare it in the line above my enums it works, however if below it doesn't, I have no idea why. If someone could explain this please go ahead.
For some functions, std::vector<T> requires that T be default-constructible. Your Enemy class cannot be default-constructed, therefore the compiler issues an error. Either define a default constructor for Enemy, do not call vector functions that require default constructibility, or change the vector to be of a different type.
Given the virtual use in Enemy, and that std::vector<Enemy> could never accept a derived class, plus your use of disgusting global variables, C arrays and otherwise terrible code, I am going to posit that you have no idea what is going on.
A std::vector<Enemy> can only ever hold an Enemy. It cannot hold a derived class of Enemy or anything else. It can only hold Enemy. If you wish to have a vector of things that might be various derived classes, you must use a pointer of some degree of ownership. This means you must solve the problem of who owns the objects being pointed to, and further that you must understand the concept of ownership and what smart pointers are available. This is essential knowledge for C++ and you won't get far without it.
To have a vector of some value type, the type must have an available no-argument constructor, which yours doesn't (ie. that's what the error message is telling you). However, since I doubt you want to copy around Enemys, you should store them by pointer,ie.
vector<Enemy*> enemies;
for (int i = 0; i < NUM_ENEMIES; ++i)
enemies.push_back(new Enemy(type));
EDIT I just noticed you have the following declaration
class Enemy...
but you also declare an enum value
enum render {... ,Enemy, ....
I just compiled the following code and got a suspiciously similar error:
#inlcude <vector>
class A {};
enum type {A, B, C};
std::vector<A> As;
int main(int argc, char** argv)
{
return 0;
}
So there's your problem. When it comes time to resolve the template, the compiler sees an enum value (which can be a template parameter, just like any other integral type), and assumes that's the one you meant. However, since no vector template matches (they all have a class as the first template parameter), it doesn't compile. Hence, your error.

"No matching constructor for initialization of. . ."

I recognize that this type of question has been asked, and I looked at those responses but still think I'm missing something. I get this "No matching constructor error", because I don't have a constructor, but that being said, everything that I looked at about constructors said that you need them if you don't already include the variable names inside the class. But I already did that, so do I need a constructor? If I do, what should it look like then? I'm new to C++, taking a class, and this is for an assignment.
Here's my sensor_node.h file with the class declaration:
#ifndef SENSORNODE_H
#define SENSORNODE_H
#include <iostream>
class LOCATION {
float lat, longi, height;
public:
LOCATION (float lat, float longi, float height);
void setx(float xx);
void sety(float yy);
void setz(float zz);
void print();
};
class SensorNode {
char* NodeName;
int NodeID;
LOCATION Node1;
float batt;
int func;
public:
SensorNode(char *n, float x, float y, float z, int i, float ah);
void print();
void setOK(int o);
int getOK();
void setLOC(float longi, float lat, float h);
};
#endif /* defined(__Project_3__sensor_node__) */
And here's my main.cpp with the error (On the line that says "LOCATION"):
#include <iostream>
using namespace std;
#include "sensor_node.h"
int main() {
LOCATION a; SensorNode s1("Pulse",15.9,-30.1,0,157,2.0);
int hold;
Actually, you so have a constructor: LOCATION (float lat, float longi, float height). Since it is the only one, C++ tries to apply it. However, you did not provide any parameters, thus this constructor does not match.
You have a constructor for LOCATION (why the inconsistent capitalisation, incidentally?) that takes three floats, but the line LOCATION a tries to call the default constructor, which you haven't defined.