C++ class critique

Shadow2531

[H]ard|Gawd
Joined
Jun 13, 2003
Messages
1,670
I've never really needed to make my own class for anything. I've always just made functions for something I needed to do, but I am curious. I made an example (just an example) function (listed first below) and then made a class to do the same thing. The class code works, but is it correct? Could I simplify it more than that? It's my first try at making a class.Thanks



Code:
#include <iostream>
#include <string>
#include <map>

using namespace std;

string getkw(const string& name) {
    map<string,string> keywords;
    keywords["test"] = "bla bla";
    return keywords[name];
}

int main() {
    cout << getkw("test") << endl;
}

Code:
#include <iostream>
#include <string>
#include <map>

using namespace std;

class kw {
    public:
        explicit kw();
        string operator[](const string& name);
    private:
        map<string,string> keywords;
};

kw::kw() {
    keywords["test"] = "bla bla";
}

string kw::operator[](const string& name) {
    return keywords[name];
}

int main() {
    kw getkw;
    cout << getkw["test"] << endl;
}
 
explicit on a constructor with no arguments is not needed. And if you want to get reaaaalllllyyy anal the operator function should probably be const and its better if the class is in a seperate cpp and h files. But that is getting super picking. All in all looks very good especially for your first time. Hell I've got some senior level developers I work with that write sloppier classes. :D
 
Thanks.

Would this be better then? (made the operator const too)

my_class.h

Code:
#ifndef SHADOW2531_MY_FIRST_CLASS
#define SHADOW2531_MY_FIRST_CLASS

#include <string>
#include <map>

class kw {
    public:
        inline kw();
        inline const std::string operator[](const std::string& name);
    private:
       std::map<std::string,std::string> keywords;
};

inline kw::kw() {
    keywords["test"] = "bla bla";
}

inline const std::string kw::operator[](const std::string& name) {
    return keywords[name];
}

#endif

Code:
#include <iostream>
#include "my_class.h"

using namespace std;

int main() {
    kw getkw;
    cout << getkw["test"] << endl;
}
 
Back
Top