Reputation: 9
I need to implement a class for one of my assignment and one of the function in the class that has string as datatype doesn't work
my definition code is :
#include <string>
class expression {
public:
expression();
void promptUser();
int getNum1();
int getNum2();
int calculate();
st::string str;
string numToString(int num);
string opToString();
private:
int num1;
int num2;
char op;
};
And in my implementation file
when I try to definite numTostring
string expression::numToString(int num) {
string digit;
...
It says that the declaration is incompatible with the header file(my class definition)
I have no idea why because both the function heading are the same.
the header file of expression.cpp( the implementation file) are :
#include "expression1.h"
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
Upvotes: 0
Views: 125
Reputation: 10415
You also need to move
#include "stdafx.h"
up so it is the first header included. The compiler ignores everything that comes before that magic line.
Upvotes: 0
Reputation: 1368
If you want to use , you need to refer to it with std::
For example, your expression class declares:
st::string str;
string numToString(int num);
string opToString();
Which should be:
std::string str; // you typed st:: instead of std::
std::string numToString(int num); // lack of std::
std::string opToString(); // lack of std::
If you dont use 2 files (cpp + h) to define and declare your class then you can add line
using namespace std;
just after your includes. This way you wont have to type std:: each time you try to refer to string and similar types. However, using this is often called a bad "beginner" practice.
If you do use cpp+h then just add std:: before every string type and add using namespace std; to your cpp file.
If you want to know more then read:
1. http://www.cplusplus.com/doc/tutorial/namespaces/
2. Why is "using namespace std" considered bad practice?
3. How do you properly use namespaces in C++?
Upvotes: 1
Reputation: 96790
Your class uses the unqualified name string
, but there is no string
data type defined in any enclosing scopes. There's a std::string
data type defined in namespace std
. That's looks to be the type that you need:
std::string str;
std::string numToString(int num);
std::string opToString();
You can keep from having to type out std::
everywhere by specifying a using
statement:
using std::string;
But you might not want to do that inside a header file, so stick with fully qualifying the type.
Upvotes: 1