我正在制作汽车设计计划。对于这个程序,我们在头文件中创建一个类,然后我们将在主程序中使用该头文件,方法是使用#include"标题名称"来包含该文件。
这是我的教授标题。这是他标题中的代码。我们被指示像他一样做头。
/*
Program 14-2
author - Ray Warren, modified from Language Companion
last updated - 19 July 2013
*/
#include <string>
using namespace std;
class CellPhone
{
private:
// Field declarations
string manufacturer;
string modelNumber;
double retailPrice;
public:
// Constructor
CellPhone(string manufact, string modNum, double retail)
{
manufacturer = manufact;
modelNumber = modNum;
retailPrice = retail;
}
// Member functions
void setManufacturer(string manufact)
{
manufacturer = manufact;
}
void setModelNumber(string modNum)
{
modelNumber = modNum;
}
void setRetailPrice(double retail)
{
retailPrice = retail;
}
string getManufacturer()
{
return manufacturer;
}
string getModelNumber()
{
return modelNumber;
}
double getRetailPrice()
{
return retailPrice;
}
}; //end class
这是他使用头文件的程序(如你所见,他包括头文件)。
/*
Program14-2
author - Ray Warren, modified from Language Companion
last updated - 19 July 2013
*/
#include <iostream>
#include <cstdlib>
#include "CellPhone.hpp"
using namespace std;
int main()
{
// Create a CellPhone object and initialize its
// fields with values passed to the constructor.
CellPhone myPhone("Motorola", "M1000", 199.99);
// Display the values stored in the fields.
cout << "The manufacturer is "
<< myPhone.getManufacturer() << endl;
cout << "The model number is "
<< myPhone.getModelNumber() << endl;
cout << "The retail price is "
<< myPhone.getRetailPrice() << endl;
system("Pause");
return 0;
} //end main
这是我的包含我的类的头文件。
#include <string>
using namespace std;
Car(int ym, string mk)
{
yearModel=ym;
make=mk;
speed=0;
}
void setYearModel(int ym)
{
yearModel=ym;
}
void setMake (string mk)
{
make=mk;
}
int returnYearModel()
{
return yearModel;
}
string returnMake()
{
return make;
}
int returnSpeed()
{
return speed;
}
void accelerate()
{
speed += 5;
}
void brake()
{
这是我的主程序,试图将头文件包含到我的主程序中。当我尝试编译它时,我的头文件弹出一个新的代码块IDE选项卡,并给了我这个错误列表。
http://prntscr.com/bzu4x5&lt; ---------错误列表
我不知道我做错了什么。从我看到的情况来看,我完全按照他告诉我们的方式复制了我的教授,而且我仍然遇到错误。
有没有人对导致这一大量错误的原因有任何想法?
#include <string>
#include <iostream>
#include "Car header.h"
int main()
{
}
答案 0 :(得分:2)
您的“头文件”包含类成员函数的定义。它实际上应该是一个.cpp文件。您缺少的是类本身的定义,以及成员函数的声明。
请注意,您教授的示例头文件定义了类定义中的成员函数。这实际上是不好的做法,但他可能还没有完成教你如何定义函数的方法。
如果 要定义函数,那么您还需要将函数更改为:
std::string Car::returnMake()
{
return make;
}
注意:“使用命名空间std”也是不好的做法。专业C ++代码往往是显式的,并使用“std ::”前缀。只要养成这种习惯,就可以节省数小时的痛苦。
答案 1 :(得分:2)
您实际上没有在头文件中定义类。请注意,在您老师的头文件中,他有:
class Cellphone // -> this is what you do not have
{
private:
// Field declarations
string manufacturer;
string modelNumber;
double retailPrice;
public:
//constructor function
CellPhone(string manufact, string modNum, double retail);
// Member functions
void setManufacturer(string manufact);
void setModelNumber(string modNum);
void setRetailPrice(double retail);
string getManufacturer();
string getModelNumber();
double getRetailPrice();
}
你应该在课堂上拥有字段和成员函数。希望有所帮助