0

我在为我的类创建对象时遇到问题,尝试使用已定义的数据成员创建类对象时遇到错误。

// class header for employee
#pragma once
#include <string>
#include <iostream>
class Employee
{
private:
    std::string name;
    int empnum;
    std::string address;
    std::string phone;
    double hourwage;
    double hoursworked;
public:
    Employee(void);
    Employee(int, std::string , std::string, std::string, double, double);
    double gethourwage () const;
    double gethoursworked () const;
    double printcheck () const;
    std::string getphone() const;
    std::string getname() const;
    std::string getaddress() const;
};
// end of header

// employee class.cpp
#include "Employee.h"
#include <string>
#include <iostream>

Employee::Employee(void)
{
    int empnum = 0;
    double hourwage = 0.0;
    double hoursworked = 0.0;
}
Employee::Employee(int num, std::string nme, std::string addres, std::string phon, double hourpay, double hrswrked)
{
    num = empnum;
    nme = name;
    addres = address;
    phon = phone;
    hourpay = hourwage;
    hrswrked = hoursworked;
}

double Employee::gethourwage() const
{
    return hourwage;
}
double Employee::gethoursworked() const
{
    return hoursworked;
}
double Employee::printcheck() const
{
    double pay = 0.0;
    double hrspay = hourwage;
    double hrswork = hoursworked;
    return hoursworked;

}
// end of employee.cpp
// main
#include <iostream>
#include <algorithm>
#include <numeric>
#include <vector>
#include <iterator>
#include <string>
#include "Employee.h"

using namespace std;
int main( )
{
    int num1 = 10210;
    double hourwage = 20.2;
    double hourworked = 32.3;
    string steve;
    Employee emp(num1, steve, 58s200w, 90210, hourwage, hourworked);
    cout << "" << emp.getaddress();

    system("PAUSE");
    return 0;
} // end of main

“员工 emp(num1, steve, 58s200w, 90210, hourwage, hourwork);” 靠近底部的是我遇到问题的那条线。我不确定我输入的顺序是否错误,或者其他什么。

提前感谢您的帮助。

4

2 回答 2

3

您应该在双引号中输入字符串:

Employee emp(num1, "steve", "58s200w", "90210", hourwage, hourworked);

编辑1(试图解释和之间的区别const char *std::string正如@Alex建议的那样)

上面代码片段中的文字字符串是 type const char *,它是从 C 语言继承的低级实体。const char *是一个指向内存区域的指针,它保存类型的连续值const char

std::string是 C 风格字符串的高级包装器,旨在提供更“用户友好”的 API 并解决 C 风格字符串的一些问题(例如,动态分配和自动内存清理)。

因为std::string该类有一个带const char *参数的构造函数,所以传递给构造函数的文字字符串被Employee隐式转换为std::string

于 2013-01-26T10:50:47.567 回答
1

您的 Employee 类构造函数是

Employee::Employee(int num, std::string nme, std::string addres, std::string phon, double hourpay, double hrswrked)

你称它为

Employee emp(num1, steve, 58s200w, 90210, hourwage, hourworked);

您可以直接看到区别,Employee 类构造函数期望第二个、第三个和第四个参数为字符串。所以你必须将这些参数作为字符串传递。要么你必须将字符串声明为你定义的小时工资、小时工作变量,要么你必须像上面解释的那样传递参数。

于 2013-01-26T11:06:26.200 回答