C++类无法识别字符串数据类型

rea*_*ash 13 c++ string constructor

我正在研究我的C++教科书中的程序,这是我第一次遇到麻烦.我似乎无法看到这里有什么问题.Visual Studio告诉我错误:标识符"string"未定义.

我将程序分成三个文件.类规范的头文件,类实现的.cpp文件和主程序文件.这些是我书中的说明:

编写一个名为Car的类,它具有以下成员变量:

一年.一个int是拥有汽车的车型年.

制作.一个string持有汽车制造的.

速度.一个int是拥有汽车的当前速度.

此外,该类应具有以下成员函数.

构造函数.构造函数应该接受car yearmakeas作为参数,并将这些值赋给对象yearmake成员变量.构造函数应该将speed成员变量初始化为0.

存取器.适当的存取器函数应创建以允许从一个对象的检索到的值year,makespeed成员变量.

有更多的说明,但没有必要让这部分工作.

这是我的源代码:

// File Car.h -- Car class specification file
#ifndef CAR_H
#define CAR_H
class Car
{
private:
    int year;
    string make;
    int speed;
public:
    Car(int, string);
    int getYear();
    string getMake();
    int getSpeed();
};
#endif


// File Car.cpp -- Car class function implementation file
#include "Car.h"

// Default Constructor
Car::Car(int inputYear, string inputMake)
{
    year = inputYear;
    make = inputMake;
    speed =  0;
}

// Accessors
int Car::getYear()
{
    return year;
}

string Car::getMake()
{
    return make;
}

int Car::getSpeed()
{
    return speed;
}


// Main program
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;

int main()
{

}
Run Code Online (Sandbox Code Playgroud)

我还没有在主程序中写任何东西,因为我无法编译类.我只将头文件链接到主程序.提前感谢所有花时间为我调查此问题的人.

rad*_*man 13

你忘了#包含字符串头,你需要完全限定你的使用stringstd::string,修改后的代码应该是.

// File Car.h -- Car class specification file
#ifndef CAR_H
#define CAR_H

#include <string>

class Car
{
private:
    int year;
    std::string make;
    int speed;
public:
    Car(int, string);
    int getYear();
    std::string getMake();
    int getSpeed();
};
#endif


// File Car.cpp -- Car class function implementation file
#include "Car.h"

// Default Constructor
Car::Car(int inputYear, std::string inputMake)
{
    year = inputYear;
    make = inputMake;
    speed =  0;
}

// Accessors
int Car::getYear()
{
    return year;
}
Run Code Online (Sandbox Code Playgroud)

你可以放在using namespace std;Car.cpp的顶部,这样你就可以在该文件中使用没有std :: qualifier的字符串.但是,不要把其中一个放在标题中,因为它是非常糟糕的mojo.

作为一个注释,您应该始终在类主体之前的头中包含类声明所需的所有内容,在包含头之前,不应该依赖包含文件(如<string>)的客户端源文件.

关于这部分任务:

构造函数.构造函数应接受汽车的年份并将其作为参数并将这些值分配给对象的年份并生成成员变量.构造函数应将speed成员变量初始化为0.

最佳实践是在构造函数中使用初始化列表,如下所示:

// Default Constructor
Car::Car(int inputYear, string inputMake)
  : year(inputYear),
    make(inputMake),
    speed(0)

{

}
Run Code Online (Sandbox Code Playgroud)


sth*_*sth 10

您应该使用完全限定名称std::string,否则您忘记包含<string>标题.或两者.


Dan*_*zey 5

我怀疑您需要#include <string>在文件顶部(使用该string类型的位置)上方。