At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/
There is the following program (I made some small modifications):
#include <iostream>
class Employee
{
public:
char m_strName[25];
int m_id;
double m_wage;
//set the employee information
void setInfo(char *strName,int id,double wage)
{
strncpy(m_strName,strName,25);
m_id=id;
m_wage=wage;
}
//print employee information to the screen
void print()
{
std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
}
};
int main()
{
//declare employee
Employee abder;
abder.setInfo("Abder-Rahman",123,400);
abder.print();
return 0;
}
When I try to compile it, I get the following:
And, why is a pointer used here? void setInfo(char *strName,int id,double wage)
Thanks.
1.
strncpy(m_strName,strName,25);
You need to #include <cstring>
(where strncpy is declared).
2.
std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
should be
std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<m_wage<<std::endl;
3.
void setInfo(char *strName,int id,double wage)
can be set to
void setInfo(const char *strName,int id,double wage)
to get rid of the g++ 4.x.x warning.
You'll have to include the header that declares the strncpy
function. So add
#include <cstring>
at the beginning.
And the member name is m_wage
but you've used it as wage
in your print
member function.
Change
std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
to
std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<m_wage<<std::endl;
^^^^^^
Add
#include <string.h>
And change wage to m_wage on line 19.
You need :
#include <string>
#include <iostream>
#include <string.h>
Regarding the last warning/error message - the first parameter of the setInfo()
member function should be declared as const char*
. Plain char*
represents pointer to a mutable character array, which string literal "Abder-Rahman"
isn't.
The error is because strncpy is declared in the cstring header file.
A pointer is used because you are working with C strings, which are char arrays. Arrays in C are used through pointers. And strncpy takes two pointers to char(char arrays) to do the copy process.