2011-01-22 104 views
1

在:http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/C++ - 类问题

有以下程序(我做了一些小的修改):

#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; 
} 

当我尝试编译它,我得到如下:

alt text

而且,为什么在这里使用了一个指针? void setInfo(char *strName,int id,double wage)

谢谢。

+0

为什么没有缩进? – 2011-01-22 14:22:19

回答

1

1.

strncpy(m_strName,strName,25); 

你需要#include <cstring>(其中strncpy()函数声明)。

2.

std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl; 

应该是

std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<m_wage<<std::endl; 

3。

void setInfo(char *strName,int id,double wage) 

可以设置为

void setInfo(const char *strName,int id,double wage) 

摆脱了G ++ 4.x.x警告。

1

添加

#include <string.h> 

而改变工资m_wage上线19

+0

请不要混合使用C++和C头文件。 – 2011-01-22 14:51:01

5

你必须包括声明strncpy函数的头。所以加上

#include <cstring> 

在开头。

成员名称为m_wage,但是您在print成员函数中使用它作为wage

变化

std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl; 

std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<m_wage<<std::endl; 
                 ^^^^^^ 
1

您需要:

#include <string> 
#include <iostream> 
#include <string.h> 
+2

请不要混合使用C++和C头文件。 – 2011-01-22 14:52:06

1

至于最后的警告/错误消息 - setInfo()成员函数的第一个参数应被声明为const char*。普通char*表示指向可变的字符数组,该字符串文字"Abder-Rahman"不是。

1

错误是因为strncpy是在cstring头文件中声明的。

使用了一个指针,因为您正在处理C字符串,它们是char数组。 C中的数组通过指针使用。并且strncpy需要两个指向char(char数组)的指针来执行复制过程。

+0

“请不要混合使用C++和C头文件。” - 康拉德鲁道夫:) – 2011-01-22 15:54:28

+0

感谢您的回复。当你说:“通过指针使用C中的数组”时,那么在C + =中如何使用数组?谢谢。 – Simplicity 2011-01-22 20:21:19