I'm a newbie in C++ and i'm trying to put a little project on wheels, but i'm having a hard time with those errors and i don't know what i'm doing wrong. I think, i've included all neccesary header files.
What i'm doing wrong?
Thank you in advance!
d:\files\visual studio 2010\projects\calculator\aplicatie.cpp(31): error C2065: 'CmdAritmetice' : undeclared identifier
d:\files\visual studio 2010\projects\calculator\aplicatie.cpp(31): error C2062: type 'int' unexpected
d:\files\visual studio 2010\projects\calculator\aplicatie.cpp(37): error C2065: 'cmd1' : undeclared identifier
d:\files\visual studio 2010\projects\calculator\aplicatie.cpp(37): error C2228: left of '.Execute' must have class/struct/union
type is ''unknown-type''
Edit
If i modify CmdAritmetice <int, Suma> cmd1("+"); with UI::CmdAritmetice<Calcule::Suma<int>> cmd1("+"); the following errors appear when try to compile:
1>d:\files\visual studio 2010\projects\calculator\aplicatie.cpp(32): error C2440: 'specialization' : cannot convert from 'T (__cdecl *)(T,T)' to 'int (__cdecl *)(int,int)'
1> None of the functions with this name in scope match the target type
1>d:\files\visual studio 2010\projects\calculator\aplicatie.cpp(39): error C2660: 'Calculator::UI::CmdAritmetice<Operatie>::Execute' : function does not take 1 arguments
1> with
1> [
1> Operatie=0x0
1> ]
Main.cpp
#include "aplicatie.h"
using namespace Calculator;
int main()
{
Aplicatie app;
app.Run();
return 0;
}
aplicatie.cpp edited
#include <iostream>
#include "aplicatie.h"
#include "Calcule\operatii.h"
#include "UI\cmdaritmetice.h"
using namespace std;
namespace Calculator{
(...)
void Aplicatie::Run()
{
TestSuma();
CmdAritmetice <int, Suma> cmd1("+"); //here i have errors
cmd1.Execute("Introduceti doua numere intregi (x, y)");
}
void Aplicatie::TestSuma()
{
int x = 10, y = 20;
int r = Calcule::Suma(x,y);
}
}
cmdaritmetice.h
#ifndef ARITMETICE_H
#define ARITMETICE_H
#include "UI\comanda.h"
namespace Calculator{
namespace UI{
template<int Operatie(int, int)>
class CmdAritmetice : public ComandaCalcule
{
public:
CmdAritmetice(const string &nume) : ComandaCalcule(nume)
{
}
void Execute()
{
cout << Nume() << endl;
cout << "Introduceti doua numere intregi (x, y)\n";
int x, y;
cin >> x >> endl;
cin >> y >> endl;
cout << x << " " << Nume() << " " << y << " = " << Operatie (x,y) <<endl;
}
};
}
}
#endif
LE
**operatii.h**
#ifndef OPERATII_H
#define OPERATII_H
namespace Calculator{
namespace Calcule{
template<typename T>
T Suma(T x, T y)
{
return x + y;
}
}
#endif
CmdAritmetice is defined in namespace Calculator::UI while Aplicatie is defined in namespace Calculator. So, you must refer to CmdAritmetice as UI::CmdAritmetice within the Calculator namespace.
As for error saying Suma cannot be found, you haven't posted the definition of Suma, so it's hard to say what's going on there, but check to make sure that that too isn't defined within some nested namespace.
EDIT:
The definition for CmdAritmetice is
template<int Operatie(int, int)>
class CmdAritmetice : public ComandaCalcule
{
// ...
};
So it takes a template argument that is function with the signature int(int, int), i.e. a function that accepts 2 ints and returns an int. Within Aplicatie::Run() you try to instantiate the class as
CmdAritmetice <int, Suma>
Obviously this will not work, the template argument needs to be a function matching the signature you've specified in the definition. Also, references to Suma need to be qualified as Calcule::Suma.
I think what you intend to do is
UI::CmdAritmetice<Calcule::Suma<int>> cmd1("+");
Related
I am still fairly new to C++, so sorry if the code is a bit amateurish, that might be the source of the problem.
I've spent some time searching this site and across the web. There are plenty of examples using enums (not enum class) and also of using enums and enums class outside of classes, but didn't really find anything useful for my particular scenario, see below. Of course, I may have seen the answer, but my C++ is not advanced enough yet to recognize it.
Basically I want to pass 2 "state" enums classes into a method, in a different class from the ones in which the enums classes are defined, and then change the state of the second enum class based on the value in the first enum class. These enum classes are defined inside a class which contains a pointer to the second class in which the method is defined. Class declarations are in header files and defined in separate .cpp files which include the relevant headers. See the detailed code and errors below.
Hoping someone can help me interpret the error messages at the end and figure out how to achieve this.
main.cpp
#include <iostream>
#include "firstfile.h"
int main() {
FirstFile firstobject;
firstobject.Function1();
}
Basically, I've got 2 enum classes inside following class.
firstfile.h
#include "secondfile.h"
class FirstFile
{
protected:
SecondFile secondobject;
public:
enum class enum1 {
Option1,
Option2
} enumIn = enum1::Option1;
enum class enum2 {
Option3,
Option4
} enumInOut = enum2::Option3;
// Methods
protected:
public:
void Function1();
};
firstfile.cpp
#include <iostream>
#include "firstfile.h"
void FirstFile::Function1()
{
std::cout << "Before the function call enumIn = Option 1 and enumInOut = Option3 " << std::endl;
secondobject.function2(enumIn, enumInOut);
if (enumInOut == enum2::Option4) {
std::cout << "After the function call enumInOut = Option 4" << std::endl;
}
else if (enumInOut == enum2::Option3) {
std::cout << "After the function call enumInOut = Option 3" << std::endl;
}
else {
std::cout << "enumInOut didn't match either Option 3 or Option 4" << std::endl;
}
}
The header file, where most of the errors occur.
secondfile.h
#include "firstfile.h"
class SecondFile
{
public:
void function2(const enum1& enumIn, enum2& enumInOut);
};
Finally, here is the method in class2 that is being called that should update enum2 based on the value of enum1.
secondfile.cpp
#include <iostream>
#include "firstfile.h"
#include "secondfile.h"
void SecondFile::function2(const enum1& enumIn, enum2& enumInOut)
{
if (enumIn == FirstFile::enum1::Option1) {
enumInOut = FirstFile::enum2::Option4;
}
}
The errors are:
firstfile.cpp
\secondfile.h(16, 28) : error C4430 : missing type specifier - int assumed.Note : C++ does not support default - int
\secondfile.h(16, 28) : error C2143 : syntax error : missing ',' before '&'
\firstfile.cpp(8, 42) : error C2660 : 'SecondFile::function2' : function does not take 2 arguments
\secondfile.h(16, 7) : message: see declaration of 'SecondFile::function2'
Main.cpp
\secondfile.h(16, 28) : error C4430 : missing type specifier - int assumed.Note : C++ does not support default - int
\secondfile.h(16, 28) : error C2143 : syntax error : missing ',' before '&'
secondfile.cpp
\secondfile.h(16, 28) : error C4430 : missing type specifier - int assumed.Note : C++ does not support default - int
\secondfile.h(16, 28) : error C2143 : syntax error : missing ',' before '&'
\secondfile.cpp(5, 39) : error C4430 : missing type specifier - int assumed.Note : C++ does not support default - int
\secondfile.cpp(5, 39) : error C2143 : syntax error : missing ',' before '&'
\secondfile.cpp(6, 6) : error C2065 : 'enumIn' : undeclared identifier
\secondfile.cpp(7, 3) : error C2065 : 'enumInOut' : undeclared identifier
Hope this all makes sense and look forward to any insights to help understand the cause of the errors and how I might be able to resolve them.
It's probably related to scope, but hoping to learn from this experience.
You have two issues:
You have circular dependencies, since you add the header of each classes to each other's header files. You can solve it via pointers members. Make the class member secondobject in the class FirstFile as a pointer, and provide a forward declaration in the header (i.e. in firstfile.h) for SecondFile.
Secondly, you need to specify the enum1 and enum2 from which class/ scope it is. You can use the using specifier for this, and enums will be available for the entire class SecondFile's scope.
That means, you need something like: (See Online)
firstfile.h
class SecondFile; // forward declaration
class FirstFile
{
protected:
SecondFile* secondobject{ nullptr }; // or smart pointers
public:
// ...enums and functions
};
firstfile.cpp
#include <iostream>
#include "secondfile.h"
void FirstFile::Function1()
{
// ...other code
if(secondobject)
secondobject->function2(enumIn, enumInOut);
// ^^^^^^^^^^^^
}
secondfile.h
#include "firstfile.h"
class SecondFile
{
public:
using enum1 = FirstFile::enum1; // specify from where the enums are
using enum2 = FirstFile::enum2;
void function2(const enum1& enumIn, enum2& enumInOut);
// ...other codes
};
secondfile.cpp
#include "secondfile.h"
void SecondFile::function2(const enum1& enumIn, enum2& enumInOut)
{
if (enumIn == enum1::Option1) {
enumInOut = enum2::Option4;
}
}
#include <thread>
#include <iostream>
#include <functional>
struct C
{
void printMe() const
{}
};
struct D
{
void operator()() const
{}
};
int main()
{
D d;
std::thread t9(std::ref(d)); // fine
t9.join();
C c;
std::thread t8(&C::printMe, std::ref(c)); // error in VS2015
t8.join();
/*
1>C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(238): error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'
1> C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(238): note: With the following template arguments:
1> C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(238): note: '_Callable=void (__thiscall C::* )(void) const'
1> C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(238): note: '_Types={std::reference_wrapper<C>}'
*/
}
http://ideone.com/bxXJem built without problems
Is the following code correct?
std::thread t8(&C::printMe, std::ref(c));
No, it doesn't compile. To compile it and make run it you need:
1) It needs to set the method printMe as a static method to send an its address (printMe's address), otherwise you are sending a relative address to instance C.
2) At the moment of create the thread t8, you are sending a reference to object C as an argument but the function printMe doesn't have arguments, So you need declare the argument into the printMe method.
3) As #cpplearner told you, send the pointer of the method as: std::thread t8(&C::printMe, &c);.
The resulting code is:
#include <thread>
#include <iostream>
#include <functional>
struct C
{
static void printMe(C* ref)
{
std::cout << "Address of C ref: " << std::hex << ref << std::endl;
}
};
struct D
{
void operator()() const
{
std::cout << "Operator D" << std::endl;
}
};
int main()
{
D d;
std::thread t9(std::ref(d)); // fine
t9.join();
C c;
std::thread t8(&C::printMe, &c); // Compile in VS2015
t8.join();
std::cout << "END" << std::endl;
}
And the output is:
I am writing a program for overloading "[ ] " operator on arrays .Here is my code
/ / A safe array example.
#include <iostream>
#include <cstdlib>
using namespace std;
class atype {
int a[3];
public:
atype(int i, int j, int k) {
a[0] = i;
a[1] = j;
a[2] = k;
}
int &operator[](int i);
};
// Provide range checking for atype.
int &atype::operator[](int i)
{
if(i<0 || i> 2) {
cout << "Boundary Error\n";
exit(1);
}
return a[i];
}
int main()
{
atype ob(1, 2, 3);
cout << ob[1]; // displays 2
cout << " ";
ob[1] = 25; // [] appears on left
cout << ob[1]; // displays 25
ob[3] = 44; // generates runtime error, 3 out-of-range
return 0;
}
In the class we are declaring as
int &operator[](int i);
and outside the class it is defined as
int &atype::operator[](int i)
It should be int atype::&operator[](int i)
but it is giving me error.
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): error C2589: '&' : illegal token on right side of '::'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): warning C4091: '' : ignored on left of 'int' when no variable is declared
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): error C2143: syntax error : missing ';' before '::'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): error C2059: syntax error : '::'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(18): error C2143: syntax error : missing ';' before '{'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(18): error C2447: '{' : missing function header (old-style formal list?)
But when I tried int &atype::operator[](int i)
it worked.Could anybody explain that are we passing reference to class or operator[](int i)
The general syntax is
<return type> class-name :: function-name (argument-list)
In your case the return type is a reference to an integer i.e. int &
int &atype::operator[](int i) is only the correct syntax
Your operator[] returns a reference to the element requested by index. In this case your array is of int type so it will be a reference-to-an-int, ie: int& as a return value.
I've been getting error C2065s for variables that I've declared in the class header file as public data members, one int and one pointer to that int. The lines of code being flagged as erroneous are only when I use these variables in a function - within the class' constructor, they appear to get through okay.
I'm using Visual Studio 2010 Express to write normal C++ (not Visual C++), and here's the output of the compiler's error log:
1>------ Build started: Project: Project 2, Configuration: Debug Win32 ------
1> BaseClassWithPointer.cpp
1>d:\libraries\documents\school\advanced c++\project 2\project 2\baseclasswithpointer.cpp(27): error C2065: 'q' : undeclared identifier
1>d:\libraries\documents\school\advanced c++\project 2\project 2\baseclasswithpointer.cpp(27): error C2541: 'delete' : cannot delete objects that are not pointers
1>d:\libraries\documents\school\advanced c++\project 2\project 2\baseclasswithpointer.cpp(32): error C2065: 'num' : undeclared identifier
1>d:\libraries\documents\school\advanced c++\project 2\project 2\baseclasswithpointer.cpp(33): error C2065: 'q' : undeclared identifier
1>d:\libraries\documents\school\advanced c++\project 2\project 2\baseclasswithpointer.cpp(34): error C2065: 'q' : undeclared identifier
1> Generating Code...
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Finally, here're my code blocks and headers:
BaseClassWithPointer.h
#pragma once
#include <iostream>
using namespace std;
class BaseClassWithPointer
{
public:
int num;
int *q;
BaseClassWithPointer();
BaseClassWithPointer(int value);
BaseClassWithPointer(const BaseClassWithPointer& otherObject);
void destroyPointer();
virtual void print();
virtual ~BaseClassWithPointer(); //Destructor is virtual so that derived classes use their own version of the destructor. ~ (2. Inheritance - base class with pointer variables – destructors.)
const BaseClassWithPointer& operator= (const BaseClassWithPointer &rhs); //Assignment operator is overloaded to avoid shallow copies of pointers. ~ (3. Inheritance – base class with pointer variables – assignment operator overloading.)
};
BaseClassWithPointer.cpp
#pragma once
#include "BaseClassWithPointer.h"
#include <iostream>
using namespace std;
BaseClassWithPointer::BaseClassWithPointer()
{
num = 0;
q = #
}
BaseClassWithPointer::BaseClassWithPointer(int value)
{
num = value;
q = #
}
BaseClassWithPointer::BaseClassWithPointer(const BaseClassWithPointer& otherObject)
{
num = otherObject.num;
q = #
}
void destroyPointer()
{
delete q;
}
void print()
{
cout << "Num: " << num << endl;
cout << "Value pointed to by q: " << *q << endl;
cout << "Address of q: " << q << endl;
}
BaseClassWithPointer::~BaseClassWithPointer()
{
destroyPointer();
}
const BaseClassWithPointer& BaseClassWithPointer::operator=(const BaseClassWithPointer &rhs)
{
if (this != &rhs)
{
num = rhs.num;
q = #
}
return *this;
}
You forgot the Class identifier for your destroyPointer() method.
Try
void BaseClassWithPointer::destroyPointer()
instead
This:
void destroyPointer()
...
void print()
Should be
void BaseClassWithPointer::destroyPointer()
{
....
}
void BaseClassWithPointer::print()
{
....
}
etc.
The function destroyPointer() is not part of the class in the cpp file.
It should be:
void BaseClassWithPointer::destroyPointer()
{
delete q;
}
but is:
void destroyPointer()
{
delete q;
}
This is why it cannot find q
Guys, why am I getting errors here?
The following was done in Visual C++
Mammal.h class file
#include <iostream>
using namespace std;
class Mammal
{
public:
//constructor
Mammal() { cout << "Mammal constructor...\n"; }
Mammal(int age) { maAge = age; cout << "Mammal age constructor...\n"; }
~Mammal() { cout << "Mammal destructor...\n"; }
//accessors
void setMaAge(int age) { maAge = age; }
void setMaWeight(int weight) { maWeight = weight; }
int getMaAge() { return maAge; }
int getMaWeight() { return maWeight; }
//other func
void speak() { cout << "Mammal Sound!...\n"; }
void maSleep() { cout << "Mammal Sleeping!...\n"; }
protected:
int maAge, maWeight;
};
Dog.h class file
#include <iostream>
#include "Mammal.h"
using namespace std;
enum BREED { golden, shepard, lab, doberman };
class Dog : public Mammal
{
public:
//constructor
Dog() { cout << "Constructing dog!...\n"; }
Dog(int age) { Mammal(age); cout << "Constructing dog with age!...\n"; }
Dog(int age, BREED breed) { Mammal(age); dogBreed = breed;
cout << "Constructing dog with age and breed!... \n"; }
Dog(int age, int weight) { Mammal(age); maWeight = weight;
cout << "Constructing dog with age and weight!...\n"; }
~Dog(){ cout << "Destruction of dog!...\n"; }
//accessors
void setDogAge(int age) { maAge = age; }
void setDogWeight(int weight) { maWeight = weight; }
void setDogBreed(BREED breed) { dogBreed = breed; }
int getDogAge() { return maAge; }
int getDogWeight() { return maWeight; }
int getDogBreed() { return dogBreed; }
//other func
void dogWagTail() { cout << "Dog Wagging Tail!...\n"; }
void dogBegFood() { cout << "Dos is Hungry!... Wants a bone.\n"; }
void speak() { cout << "Dog Sound: Wof, Wof!\n"; }
private:
BREED dogBreed;
};
main.cpp file
#include <iostream>
#include "Mammal.h"
#include "Dog.h"
using namespace std;
int main()
{
Mammal fourLegs;//const mammal
Dog Champ;//const dogs
Dog Pimp(4, lab);
Dog Mango(2, 54);
fourLegs.speak();
Champ.speak();
Champ.setDogBreed(doberman);
Pimp.setDogWeight(123);
cout << "Pimp is: " << Pimp.getDogAge() << " years old - Weight: " << Pimp.getDogWeight()
<< " pounds - breed: " << Pimp.getDogBreed() << endl;
Mango.dogWagTail();
system("pause");
return 0;
}
errors:
1>------ Build started: Project: Overriding, Configuration: Debug Win32 ------
1> main.cpp
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\mammal.h(5): error C2011: 'Mammal' : 'class' type redefinition
1> c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\mammal.h(5) : see declaration of 'Mammal'
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\dog.h(6): error C2504: 'Mammal' : base class undefined
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\dog.h(10): error C2079: 'age' uses undefined class 'Mammal'
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\dog.h(10): error C2082: redefinition of formal parameter 'age'
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\dog.h(11): error C2079: 'age' uses undefined class 'Mammal'
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\dog.h(11): error C2082: redefinition of formal parameter 'age'
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\dog.h(13): error C2079: 'age' uses undefined class 'Mammal'
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\dog.h(13): error C2082: redefinition of formal parameter 'age'
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\dog.h(13): error C2065: 'maWeight' : undeclared identifier
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\dog.h(17): error C2065: 'maAge' : undeclared identifier
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\dog.h(18): error C2065: 'maWeight' : undeclared identifier
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\dog.h(20): error C2065: 'maAge' : undeclared identifier
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\dog.h(21): error C2065: 'maWeight' : undeclared identifier
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\main.cpp(8): error C2079: 'fourLegs' uses undefined class 'Mammal'
1>c:\users\jorge\documents\visual studio 2010\projects\overriding\overriding\main.cpp(12): error C2228: left of '.speak' must have class/struct/union
1> type is 'int'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
any help appreciated
Read this:
1>c:\users\jorge\documents\visual
studio
2010\projects\overriding\overriding\mammal.h(5):
error C2011: 'Mammal' : 'class' type
redefinition
Now, when your program compiles (starts from main.cpp) it includes iostream, then Mammal.h, then Dog.h.
When including Mammal.h and Dog.h program includes also all the includes from those files also.
So, Mammal.h is included first from main.cpp and then from Dog.h
To remove this error, simply use #ifndef, #define and #endif like this:
#ifndef _MAMMAL_H
#define _MAMMAL_H
#include <iostream>
using namespace std;
class Mammal
{
public:
//constructor
Mammal() { cout << "Mammal constructor...\n"; }
Mammal(int age) { maAge = age; cout << "Mammal age constructor...\n"; }
~Mammal() { cout << "Mammal destructor...\n"; }
//accessors
void setMaAge(int age) { maAge = age; }
void setMaWeight(int weight) { maWeight = weight; }
int getMaAge() { return maAge; }
int getMaWeight() { return maWeight; }
//other func
void speak() { cout << "Mammal Sound!...\n"; }
void maSleep() { cout << "Mammal Sleeping!...\n"; }
protected:
int maAge, maWeight;
};
#endif
Always include #ifndef #define AND #endif in all your .h files.
Besides inclusion guards, in Dog object you are initializing Mammal object wrong way, you should initiliaze your base class like this;
Dog(int age) : Mammal(age) { ... }
You should be using include guards in your headers.
main.cpp is including Mammal.h before including Dog.h which itself includes Mammal.h. This means that the Mammal class is being redefined within main, hence the compiler errors. Include guards protect you from this.
you should protect your headers
#ifndef _MAMMAL_H_
#define _MAMMAL_H_
class Mammal {
...
};
#endif
#ifndef _DOG_H_
#define _DOG_H_
class Dog {
...
};
#endif