I've been getting errors all day when I tried to use return reference or pointer in c++. Please tell me what should I change in code below to return Config class members by reference or pointer.
#include <cstdlib>
#include <iostream>
using namespace std;
class JustExample {
public:
string someText;
JustExample() {
someText = "blablabla";
}
};
class Config
{
public:
Config();
string getResourceDir() const;
JustExample getExmp() { return exmp; }
void setResourceDir(const string& dir);
void setExmp(JustExample example) { exmp = example; }
private:
JustExample exmp;
string res_dir;
};
Config::Config() {
res_dir = "class value";
}
string Config::getResourceDir() const { return res_dir; }
void Config::setResourceDir(const string& dir) { res_dir = dir; }
int main(int argc, char *argv[])
{
Config cfg;
cout << cfg.getResourceDir() << endl;
cfg.setResourceDir("changed");
cout << cfg.getResourceDir() << endl;
cout << cfg.getExmp().someText << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Bonus question. Why can't I initialize variables after their declaration but have to assign their value in class constructor instead or I get an error.
8 D:\projects\dev-cpp test\main.cpp ISO C++ forbids initialization of member `someText' 8 D:\projects\dev-cpp test\main.cpp making `someText' static 8 D:\projects\dev-cpp test\main.cpp invalid in-class initialization of static data member of non-integral type `std::string' D:\projects\dev-cpp test\main.cpp In function `int main(int, char**)': 38 D:\projects\dev-cpp test\main.cpp 'class JustExample' has no member named 'someText' D:\projects\dev-cpp test\Makefile.win [Build Error] [main.o] Error 1
JustExample& /* << ADDED THERE */ getExmp() { return exmp; }? - Ben Voigtstring someText = "blablabla";as a class member ? - M.MJustExampleis entirely different to the question aboutConfig's getter/setters - M.M