我在为类创建对象时遇到问题,尝试使用已定义的数据成员创建类对象时出错。
// 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
“Employee emp(num1,steve,58s200w,90210,hourwage,hourworked);”最底层的是我遇到的问题。我不确定我是以错误的顺序输入它还是别的。
提前感谢您的帮助。
答案 0 :(得分:3)
您应该用双引号输入字符串:
Employee emp(num1, "steve", "58s200w", "90210", hourwage, hourworked);
修改1(尝试解释const char *
和std::string
之间的区别,正如@Alex建议的那样)
上面代码段中的文字字符串属于const char *
类型,它是从C语言继承的低级实体。 const char *
是内存区域的指针,其中包含const char
类型的连续值。
std::string
是C风格字符串的高级包装器,旨在提供更多“用户友好”的API并解决C风格字符串的一些问题(例如,动态分配和自动内存清理)。 / p>
因为std::string
类有一个带const char *
参数的构造函数,传递给Employee
构造函数的文字字符串会隐式转换为std::string
的
答案 1 :(得分: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类构造函数期望第2,第3和第4个参数为String。所以你必须将这些参数作为字符串传递。您必须将字符串声明为hourwage,按照您的定义声明小工作变量,或者您必须按照上面解释的名称传递参数。