Reputation: 41
I am trying to print out a C string that is stored in a class by returning the value using an accessor function.
Thanks for any help!
This is the error I get when I compile:
cstringClass.cpp: In member function 'char Foo::get_name()':
cstringClass.cpp:37:9: error: invalid conversion from 'char*' to 'char' [-fpermi
ssive]
return name;
^
Here is the code:
#include <iostream>
#include <cstring>
using namespace std;
class Foo
{
public:
void set_name(char a[]);
char get_name();
private:
char name[10];
};
int main()
{
Foo bar;
char a[10] = "Test";
bar.set_name(a);
cout << bar.get_name();
return 0;
}
void Foo::set_name(char a[])
{
strcpy(name, a);
}
char Foo::get_name()
{
return name;
}
Upvotes: 0
Views: 184
Reputation: 529
As the error message states, your get_name()
function doesn't return the appropriate type, which should be char*
based on the data it returns, which is name[10]
. char
returns only 1 byte of data and name[10]
has 10. Please see the corrected code below.
#include <iostream>
#include <cstring>
using namespace std;
class Foo
{
public:
void set_name(char a[]);
char *get_name(); //<-- correction
private:
char name[10];
};
int main()
{
Foo bar;
char a[10] = "Test";
bar.set_name(a);
cout << bar.get_name();
return 0;
}
void Foo::set_name(char a[])
{
strcpy(name, a);
}
char *Foo::get_name() //<-- correction
{
return name;
}
Upvotes: 1
Reputation: 85897
So the error says:
cstringClass.cpp: In member function 'char Foo::get_name()':
^^^^^^^^^^^^^^^^^^^^
And indeed:
char get_name();
You declared get_name
as returning a single char
, not a pointer to a string. You probably meant char *get_name();
.
Upvotes: 2