0
The code below is showing syntax error in visual studio. Please help me figure out the error😅😅
// Header File #ifndef MYCLASS_H #define MYCLASS_H class Myclass { public: Myclass(string a, string b); private: string var1; const string var2; }; #endif // Source File #include "Myclass.h" #include <iostream> using namespace std; Myclass::Myclass(string a, string b) : var1 (a), var2 (b) { cout << var1 << endl; cout << var2 << endl; } int main(){ MyClass obj("Hello", "World"); } // THE END
5 Réponses
- 1
Thanks Andriy. But there was another error that is now figured out.
The line "using namespace std;" should be written under the string header declaration in the header file.
Rather, thanks🙂🙂
+ 3
You didn't include string header to use string class.
Header file should be like this:
#ifndef MYCLASS_H
#define MYCLASS_H
#include <string>
class Myclass
{
public:
Myclass(std::string a, std::string b);
private:
std::string var1;
const std::string var2;
};
#endif
also you have spelling error inside main function. It should be:
Myclass obj("Hello", "World");
(not MyClass)
+ 2
don't write line
using namespace std;
in header files.
This is bad programming style! (You get some problems when you will use other namespaces in C++ file which includes your header with using namespace std)
Use it only inside C++ file.
In header file use namespace prefix instead. (std::)
I wrote code with namespace prefixes.
May be you forgot to insert std:: prefix before some strings?
+ 2
@BILAL AHMAD BHAT
This is not an error.
var2 is member of the class. It is initialized in the constructor. It is allowed.
0
string var2 is const.. so it needs to be initialized at the time of declaration.. you can't keep a const variable uninitialized, it can't be initialized later.