C++ - class issue

前端 未结 6 1624
灰色年华
灰色年华 2021-01-24 19:33

At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

There is the following program (I made some small modifications):

#include 

        
相关标签:
6条回答
  • 2021-01-24 19:45

    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;
                                                             ^^^^^^
    
    0 讨论(0)
  • 2021-01-24 19:46

    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.

    0 讨论(0)
  • 2021-01-24 19:55

    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.

    0 讨论(0)
  • 2021-01-24 19:57

    You need :

    #include <string>
    #include <iostream>
    #include <string.h>
    
    0 讨论(0)
  • 2021-01-24 19:58

    Add

    #include <string.h>
    

    And change wage to m_wage on line 19.

    0 讨论(0)
  • 2021-01-24 20:00

    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.

    0 讨论(0)
提交回复
热议问题