I was practicing pointers and classes and I tried to print the members of the class after I put a value. But an error appears that's something to do with pointers and the char array.
Error (active) E0167 argument of type "const char *" is incompatible with parameter of type "char *"
Error (active) E0167 argument of type "const char *" is incompatible with parameter of type "char *"
Error C2664 'void car::setName(char [])': cannot convert argument 1 from 'const char [4]' to 'char []'
Error C2664 'void car::setColor(char [])': cannot convert argument 1 from 'const char [4]' to 'char []'
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
class car {
private:
char name[15];
char color[10];
int maxspeed;
int model;
public:
void setName(char n[])
{
strcpy_s(name, n);
}
void setColor(char n[])
{
strcpy_s(color, n);
}
void setMaxspeed(int m)
{
maxspeed = m;
}
void setModel(int m)
{
model = m;
}
char* getName()
{
return name;
}
char* getcolor()
{
return color;
}
int getMaxspeed()
{
return maxspeed;
}
int getModel()
{
return model;
}
void print()
{
cout << "name = " << name << "\n"
<< "color = " << color << "\n"
<< "Maxspeed = " << maxspeed << "\n"
<< "Model = " << model << "\n";
}
};
int main()
{
car x;
x.setName("kia");
x.setColor("red");
x.setMaxspeed(300);
x.setModel(2017);
x.print();
return 0;
}
Those are the errors I got (https://i.stack.imgur.com/xTx7E.png)
CodePudding user response:
It's telling you the problem fairly directly. You're trying to pass string literals to setName
and setColor
. To be compatible with a string literal, you need an argument of type char const *
(or equivalently, const char *
). But what you've used is char []
, which (in the case of a function argument) is equivalent to char *
.
So, change the arguments to char const *
:
void setName(char const *n)
{
strcpy_s(name, n);
}
Once you've done that, look up std:string
, and (unless required for homework or similar) quit using raw pointers to char
.
CodePudding user response:
In C , char*
(or char[]
, as you wrote it) is a different type than const char*
and string literals are of the latter. You can't pass a const char*
to a function expecting char*
.
If you rewrite your functions to take const char*
or const char[]
, it'll work:
void setColor(const char n[])
// ...
void setColor(const char n[])
// ...