C ++ - 类问题 [英] C++ - class issue

查看:161
本文介绍了C ++ - 类问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

  #include< iostream> 

class Employee
{
public:
char m_strName [25];
int m_id;
double m_wage;

//设置员工信息
void setInfo(char * strName,int id,double wage)
{
strncpy(m_strName,strName,25)
m_id = id;
m_wage = wage;
}

//将雇员信息打印到屏幕上
void print()
{
std :: cout<<Name:< ;< m_strName<<id:<< m_id<<working:$<<<< std :: endl;
}
};

int main()
{
//声明员工
Employee abder;
abder.setInfo(Abder-Rahman,123,400);
abder.print();
return 0;
}



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





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



谢谢。

$ b $

  strncpy(m_strName,strName, 25); 

您需要 #include< cstring> (其中声明了strncpy)。



2。

  std :: cout<<Name:<<<<< 

应为

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

3。

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

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



以摆脱g ++ 4.xx警告。


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.

这篇关于C ++ - 类问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆