C++接口(标头)和实现文件不起作用

C++ Interface (Header) and Implementation File Won't Work

本文关键字:实现 文件 不起作用 接口 标头 C++      更新时间:2023-10-16

我正在上C 类,由于某些原因,我无法将标题文件中的类在我的一个程序上工作。我正在使用Visual Studio 2017,并且通过在Visual Studio中使用Solution Explorer。

我的程序中有两个构造函数,一个默认值,一个没有。我尝试从每个文件中删除第二个文件,然后程序运行,但我无法使其工作。

标题文件:

#pragma once
class BuckysClass {
public:
BuckysClass();
BuckysClass(string);
void coolSaying();
};

实现文件:

#include "stdafx.h"
#include <iostream>
#include "BuckysClass.h"
#include <string>
using namespace std;
BuckysClass::BuckysClass() {
   cout << "Bucky is ";
}
BuckysClass::BuckysClass(string x) {
   cout << x;
}
void BuckysClass::coolSaying() {
   cout << "preachin to the choir" << endl;
}

测试文件:

#include "stdafx.h"
#include <iostream>
#include <string>
#include "BuckysClass.h"
using namespace std;
int main() {
BuckysClass buckysObject;
buckysObject.coolSaying();
BuckysClass buckysObject2("Bucky is not ");
buckysObject2.coolSaying();
system("Pause");
return 0;
}

语法错误:标识符'字符串'

#include <string>//include the string header
class BuckysClass {
public:
  BuckysClass();
  BuckysClass(std::string);//add the namespace identifier
  void coolSaying();
};

您的标题文件buckysclass.h不包括<string>标头文件。

add:

#include<string>
using namespace std;

您应该从相应的.cpp文件中删除这些内容,然后将BuckySclass.h保留在CPP文件中。

这是测试文件的更多图片,我收到的错误消息我无法发布。

测试文件

错误消息