HI.
How can I define a bool method in .h file and work with it in the cpp file?
I have
my.h
#include <string>
public class me;
class me
{
public:
me();
private bool method(string name); //it is ok??
}
my.cpp
#include 'my.h';
me::me()
{
method(string name); //can i do this? isn't there another alternative?
}
method (String name)
{
cout<<"name"<<endl;
}
is not working.why?
I suggest you learn the basics of C++ from a tutorial
my.h
#include <string>
class me
{
public:
me();
bool method(std::string name) const;
};
my.cpp
#include 'my.h';
me::me()
{
}
bool me::method(std::string name)
{
std::cout << name << std::endl;
}
As written, there is no need for me::method to be a member function (it could be a static).
Numerous little fixes there. I get the sense that you are coming from C# (possibly java). Read up on the differences. Google has good sources :)
There are a number of issues with your code.
my.h
#include <string>
// public class me; // Absolutely not needed. From which language did you get this?
class me
{
public:
me();
private: // You need the colon here.
bool method(string name); //it is ok?? // No. The class is called std::string. You should pass it by const-reference (const std::string& name);
}
my.cpp
#include 'my.h';
me::me()
{
// `name` is undefined here. You also don't need to specify the type.
//method(string name); //can i do this? isn't there another alternative?
method("earl");
}
// method (String name) // See previous comment about const-reference and the name of the class. Also note that C++ is case-sensitive. You also need to specify the return type and the class name:
bool me::method(const std::string& name)
{
// cout<<"name"<<endl; // Close...
std::cout << "My name is " << name << std::endl;
return true; // we are returning a `bool, right?
}
You'll also need to call your code:
int main()
{
me instance_of_me;
return 0;
}
I suggest you take a look for a good C++ tutorial and some reading material.
Answers to questions in the comments:
could you please tell me why do I need to pass std::string through reference?
This question has already been asked (more than once) on StackOverflow. I recommend this answer.
And what is with me mo?
In hindsight mo was a terrible choice for a variable name. instance_of_me may have been a better choice. This line constructs an instance of me, calling the constructor (which in turn calls method("earl"))
You meant me method("hello"); in the main()
I certainly did not!
You declared method as a private member function. This method cannot, therefore, be called from outside the class.
First of all, you have missed : after private
Second, if method (String name) in the cpp file should be the method (String name) from your class, it must be:
bool me::method(std::string name)
{
// ...
}
Third, if you want this bool me::method(std::string name) to be different function, a global one, not from you class, it must be:
ret_type method(std::string name)
{
// ...
}
And, fourth,
cout<<"name"<<endl;
will pring the string (literal) "name". If you want to print the variable name, use it without the quotes:
std::cout<< name <<endl;
I'd recommend you to get a book
Ah, and this one:
me::me()
{
method(string name); //can i do this? isn't there another alternative?
}
method(string name) - this is not valid syntax. It should be something like:
me::me()
{
string name;
// do something with name
method( name ); // if "method" is a method, for real
}
Related
So I'm an newbie to programming and I have encountered a
case for which I suppose qualifies as an authentic question
in this awesome forum. Is there a way to write statements inside my get functions so that I can obtain all the changed data member values without having to create multiple get functions
for each data member?
Regards
I am practicing building programs which are easy to maintain by localizing the effects to a class's data members by accessing and manipulating the data members through their get and set functions. In this regard I have two data members for which I wish to change. After compiling, the set functions works well by changing the values but the get functions can only return one of the data member values at a time.
class GradeBook
{
public:
void setCourseName(string code,string name)
{
CourseCode = code;
CourseName = name;
}
string getCourseName()
{
return CourseCode;
return CourseName;
}
void displayMessage()
{
cout<<"Welcome to the GradeBook for: \n" <<getCourseName()
<<endl;
}
private:
string CourseName;
string CourseCode;
};//end class GradeBook
After compiling and running the program, the program outputs the CourseCode but the CourseName doesn't get displayed. I had to create two get functions each to obtain the two data members. I don't want to have 2 get functions to obtain the data member values. I just want to use one get function to keep the code at minimum.I wish to use one get function to return two values for each data member. I have already tried using one return statement and separated the data members with a comma.
Your idea of using return twice cannot work, the first return will return control to the caller and the second will never be executed. You should have got warning about it from your compiler.
I believe that an initial solution could be to use std::pair (docs: https://en.cppreference.com/w/cpp/utility/pair), see snippet below.
NOTE: using namespace std; (which is most likely what you are doing in the code you do not show), is a bad practice, consider using the fully qualified name
#include <string>
#include <utility>
#include <iostream>
//Bad practice, I added it only to keep differences with OP code small
using namespace std;
class GradeBook
{
public:
void setCourseName(string code,string name)
{
CourseCode = code;
CourseName = name;
}
std::pair<string, string> getCourseName()
{
return {CourseCode, CourseName};
}
void displayMessage()
{
//only in C++17
auto [code, name] = getCourseName();
cout<<"Welcome to the GradeBook for: \n" << code << " - " << name
<<endl;
}
private:
string CourseName;
string CourseCode;
};//end class GradeBook
Note that auto [code, name] is a feature called structured binding, available only in C++17, if you have an older compiler, you have to return a std::pair<std::string, std::string> and access its elements using the member variables first and second.
Now, std::pair is good for this contrived example, but, for your case, you might want to consider doing something a bit more readable, because the elements of the pair have the same type so the user of your library will have difficulties remembering what is the first and second element. So you might want to use a custom-made struct with some more meaningful names.
#include <string>
#include <utility>
#include <iostream>
//Bad practice, I added it only to keep differences with OP code small
using namespace std;
struct CourseCodeAndName{
std::string code;
std::string name;
};
class GradeBook
{
public:
void setCourseName(string code,string name)
{
CourseCode = code;
CourseName = name;
}
CourseCodeAndName getCourseName()
{
return {CourseCode, CourseName};
}
void displayMessage()
{
auto codeAndName = getCourseName();
cout<<"Welcome to the GradeBook for: \n" << codeAndName.code << " - " << codeAndName.name
<<endl;
}
private:
string CourseName;
string CourseCode;
};//end class GradeBook
See this example. Alternatively you can use std::tuple.
class GradeBook
{
/* ... */
public:
std::pair<std::string, std::string> get(){
return std::make_pair(CourseName, CourseCode);
}
};
int main()
{
GradeBook book1("Hello","World")
auto result = book1.get();
cout << result.first << result.second;
}
If you write:
return x,y;
or:
return x;
return y;
You should know that in first case you get the last value (you get y), and in second case you get the value of first return (you get x, because as soon as compiler see return, function will return the value, and then function will go in epilogue state (cleaning of stack memory assigned to function, both inline and non-inline function).
And about the use of get function it's normal. If you want to use the value to do something of logic (not to display), yes you should use a lot of get function. Instead if you want to display the values, use a void function, for example "void printData();", and inside it write code to print data. You probably setted the class variables as private (following the encapsulation rules) so you will have access to them inside the print function.
I'm trying to read a file and store it in a protected variable. All methods are in the same class.
class A: public B
{
public:
//method declarations
protected:
string d;
};
void A::l(std::string filename)
{
ifstream ifs;
ifs.open(filename);
string d { istreambuf_iterator<char> {ifs}, istreambuf_iterator<char> {} };
ifs.close();
}
void A::f(void)
{
std::cout << d.length() << std::endl;
}
When I try to print the length of the string, it is 0. When I try to print d in f(), nothing is printed. I need d to be a protected variable and I cannot change the methods either. How do I pass the read file string to f method?
You assigned to a local, use the member (this-> is optional here):
this->d.assign(istreambuf_iterator<char> {ifs}, {});
If that doesn't help, you're probably specifying the file name wrong.
Try an absolute path (e.g. /home/user/file.txt or C:\Documents\User\Documents\file.txt) or check the working directory of your program.
You can always check for errors:
if (!ifs) throw std::runtime_error("File could not be opened");
Your problem has nothing to do with the fact that your variable is protected. The problem is that you are defining another variable with the same name. To avoid this problem some people append an underscore to the name of the variables, like 'd_', and other people write 'm_d'. But you don't need to do that if you don't want to.
One way to do what you want to do is the following:
class A
{
public:
void l(std::string filename);
void f();
//method declarations
protected:
string d;
};
void A::l(std::string filename)
{
ifstream ifs{filename};
if(!ifs)
return; // error
std::copy(istreambuf_iterator<char>{ifs},
istreambuf_iterator<char>{},
std::back_inserter(d)); // this is A::d
}
You don't need to use 'this->'. In fact in C++ you never use 'this' (only in sentences like 'return *this').
Also, in C++ you don't write:
void f(void);
but instead, you write
void f();
And also you don't need to close the ifstream. The destructor is going to do it for you.
Section 9(1/4) out of 11 of my c++ introduction webclass;
I have no idea what I'm doing.
I'm unsure even of what terms to search for(first touch with OOP).
-
I need to print the cin in main with a function in a class,
So far I have come up with a class with a string variable and a function that do nothing;
#include <iostream>
#include <string>
using namespace std;
class printclass
{
public:
string array;
void print();
};
void printclass::print()
{
cout << array;
}
Main program(cannot be edited);
int main()
{
char array[50];
cout << "Enter string:";
cin.get(array, 50);
printclass printer;
printer.print(array);
}
It is my understanding that the printclass printer; creates an object 'printer' with the printclass class and thus knows how to use the functions in the class
on sort-of a blank page that is declared with the call, am I far off?
How do I print the value of the array in main with the function?
The exercise has been translated from finnish, please excuse blunt grammar and user stupidity.
Thank you for your time!
am I far off?
Kinda. You've incorrectly assumed the interface of your printclass. Here's a correct one1 from the example posted:
class printclass {
public:
printclass();
void print(const char* str);
};
From that it's quite easy to spot your mistake; you've assumed that your class has to store the array to print, while the interface passes it directly. It's enough to implement the print in terms of str without any member variables:
void printclass::print(const char* str) { // could be const
std::cout << str;
}
Note: the constructor can of course be left alone and it will default to what you want.
1One of many possible interfaces, but I've picked the most likely.
I'm trying to initialize a private variable of my Class passing a const string &aString to it as parameter.
Here's my method:
void Image::initWithTextureFile(const std::string &inTextureName)
{
Texture2D *imTexture = TEXTURE_MANAGER->createTexture(inTextureName);
if(imTexture)
{
texture = imTexture;
scale = 1.0f;
name = inTextureName; //name is a private string variable inside my class
initImplementation();
}else {
printf("Could not load texture when creating Image from file %s\n",inTextureName.c_str());
}
}
My problem is the following, when I call this method I do it like:
myInitializer.initWithTextureFile("myFile.bmp");
When I'm inside the scope of initWithTextureFile the name variable takes the value of inTextureName. For this example if I cout << name << endl; inside initWithTextureFile i would get "myFile.bmp"
But when I leave the scope of the function, name looses it's value, so when i cout << name << endl; I get nothing printed in the console.
Could anyone point me out to what's going on here?
Name is declared:
private:
std::string name;
If you're outside the class scope, and cout << name compiles at all, it means you have another variable named name, and that's what's being picked up. If you want to refer to it outside the class, you'll have to come up with a way that will export it. You might, for example, have a member function like const std::string &GetName() { return name; }.
You either omitting something in your description or are not showing appropriate code that could help solve your problem.
This works:
#include <iostream>
#include <string>
using namespace std;
struct A
{
void f(const string& str) { name = str; }
void g() { cout << name << endl; }
string name;
};
int main()
{
A a;
a.f("test");
a.g();
}
Output:
test
That should work. Are you sure it is not being modified somewhere else, such as in initImplementation?
The problem probably have to do with the name variable : is it a pointer or ref to string instead of a plain string ?
The only reasonable explanation here is that you must be working with two different name objects. The one you declared as a class member should hold its value when you exit the method. It is just that outside the class method you must be printing a completely different name, which is empty.
I was going to say something about short-lived stack objects but I realised that was wrong. What it could be is something to do with exporting the containing class from a DLL.
If so, you might find a warning like this:
c:\yourclass.h(7): warning C4251: 'YourClass::name_' : class 'std::basic_string<_Elem,_Traits,_Ax>' needs to have dll-interface to be used by clients of class 'YourClass'
This thread describes more.
How is 'name' declared? It seems like maybe it's declared as a reference instead of an object.
Try:
name = std::string(inTextureName);
I am very new to C++ and still trying to learn syntax and best practices.
I've defined a method with a single parameter:
void foo(const std::string& name)
1) Is this a proper parameter declaration for a function that will be taking in a string defined by the user in, for example, a main method?
2) If this is proper/recommended syntax, what would an instantiation of a sample parameter look like?
Yes, that is the correct syntax. You can call it and provide parameters several different ways:
With a string literal:
foo("bar");
With a string variable:
std::string b = "bar";
foo(b);
With the result of a function return type string:
std::string quux();
foo(quux());
With a char* variable:
int main(int argc, char const* argv[]) {
foo(argv[0]);
}
I'm not sure if I fully understand your question, but I'll try to clarify it.
You use the terminology 'method'. I'm assuming that your method is encapsulated in a class? If so, then :-
In your header file (eg. source.h),
class dog
{
...
public:
void foo(const std::string &name);
...
};
In your source file (eg. source.cpp)
void dog::foo(const std::string &name)
{
// Do something with 'name' in here
std::string temp = name + " is OK!";
}
In your 'main' function, you can instantiate your 'dog' class, and call the 'foo' function like :-
void blah()
{
dog my_class;
my_class.foo("Testing my class");
}
If you want a function (ie. a 'method' that is not encapsulated within a class), then what you have is correct.
In your source file (eg. source.cpp)
void foo(const std::string &name)
{
// Do something with 'name' in here
std::string temp = name + " is OK!";
}
If you want to be able to call your function from outside that particular source file, you'll also need to forward declare your function in a header file.
In your header file (eg. source.h)
void foo(const std::string &name);
To call your function,
void blah()
{
foo("Testing my class");
}
Hope this helps!
1)
It is a proper parameter declaration if function foo() doesn't mean to change the string. The 'const' keyword is used to signify that the string won't be changed by the receiver.
If you write code in foo() which modifies the string you will get compiler error/warning.
2)
std::string theString = "Hello";
foo( theString );
Is this a proper parameter declaration for a function that will be taking in a string defined by the user in, for example, a main method?
Yes.
#include <string>
using namespace std;
void foo(const string& name)
1) Yes, that's a very good way to do it if you only need to read the string in the function.
2) There is no instantiation going on?
1) For most functions, it would be a fine signature. However, since you mentioned main(), there are only two valid signatures:
int main()
int main(int argc, const char* argv[])
...as you can see, you have to use C-style strings due to C-legacy compatibility (and efficiency)
2) Not sure I understand your second question, but since std::string has a constructor that takes a const char*, you can just say:
foo("hello");
or:
std::string input;
std::cout << "Enter some text: ";
std::cin >> input;
foo(input);