I have written program in c++. First I have wrote it normally (normally I do not write in c++) and I wanted put variables in header and code in .cpp file. The problem is that class in .cpp do not see variales - "Identifier is undefined".
a.h
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
using namespace std;
class Hex {
private:
int n;
string value;
bool negative = false;
public:
Hex();
bool isCorrect();
string getValue();
void setValue();
};
a.cpp
#include "a.h"
#include "stdafx.h"
class Hex {
public:
Hex(int n, string w) { //some implementation }
//rest class
}
What I'm doing wrong? If it is important I'm working on VS 2013.
Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.
The short answer is that a . h file contains shared declarations, a . cpp file contains definitions and local declarations. It's important that you understand the difference between declarations and definitions.
Cpp files don't always have to have a header file associated with it but it usually does as the header file acts like a bridge between cpp files so each cpp file can use code from another cpp file. One thing that should be strongly enforced is the no use of code within a header file!
h is deprecated and not a standard header. It was used in older programs before C++ was standardized, Functions like cout were defined inside iostream. h . After C++ got standardized, all these functions like cout got moved into the std namespace.To adjust to this change, non .
You're defining your class twice, once in the header file and the once in the .cpp file. Assuming you want to just declare functions in the header file and define them in the .cpp file this is the way to go : header:
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
using namespace std;
class Hex {
private:
int n;
string value;
bool negative;
public:
Hex(int n, string w);
bool isCorrect();
string getValue();
void setValue();
};
.cpp file:
#include "a.h"
#include "stdafx.h"
Hex::Hex(int n, string w) : negative(false) { /*some implementation*/ }
//rest class and definitions of bool isCorrect(); string getValue(); void setValue();
In the header you're declaring it as Hex();
but in the .cpp you're declaring it as Hex(int n, string w)
Also why not defining it like this Hex::Hex(){//some implementation }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With