I have this code below and I'm getting the error upon compilation:
error: cannot convert 'const char*' to 'std::string*' for argument '1' to 'void sillyFunction(std::string*, int)'
#include <iostream>
#include <string>
using namespace std;
int counter = 0;
void sillyFunction(string * str, int cool=0);
int main(){
sillyFunction("Cool");
sillyFunction("Cooler", 1);
return 0;
}
void sillyFunction(string * str, int cool){
counter++;
if (cool){
for (int i=0; i<counter; i++) cout << *str << endl;
} else {
cout << *str << endl;
}
}
Don't take your parameter in as a string *
try just using a const string &
instead
EDIT:
std::string
and const char*
are different types. the std::string
already has a conversion from string literals (ex: "Cool"
) to the actual string object. So by passing in the string literal "Cool"
you are in a sense passing in a std::string
object, not a pointer to one.
The reason I chose to use a const string &
is mostly from personal coding practices. This minimizes stack memory usage, and since you are passing in a constant string literal, there is no need for the parameter to be modify-able.
Also don't forget if you change from a string *
that you no longer need to dereference it in your cout
:
if (cool){
for (int i=0; i<counter; i++) cout << str << endl;
} else {
cout << str << endl;
}
change
void sillyFunction(string * str, int cool){
counter++;
if (cool){
for (int i=0; i<counter; i++) cout << *str << endl;
} else {
cout << *str << endl;
}
}
to
void sillyFunction(const char* str, int cool){
counter++;
if (cool){
for (int i=0; i<counter; i++) cout << str << endl;
} else {
cout << str << endl;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With