问题描述
我只是在尝试编译一个包含.cpp和.h(用于VS代码目的的.hpp)的简单程序。 每当我将构造函数的实现放在.hpp文件中并且不包括.cpp时,代码就会编译。但是,每当我将实现分离到.cpp文件中时,我都会得到
error: use of undeclared identifier 'std' LinkedChar::(std::string s)
我尝试过包括头枕,但使用#pragma一次,我仍然遇到相同的错误。 这是我的main.cpp
#include "LinkList.hpp"
int main()
{
LinkedChar("h");
return 0;
}
这是我的.hpp文件
#pragma once
#include "LinkList.cpp"
#include <iostream>
#include <string>
//Create a LinkList
class Node
{
public:
Node *next;
char data; //The data will hold a character
};
class LinkedChar
{
public:
//LinkedChar(): head(NULL),tail(NULL){}
LinkedChar(std::string s);
private:
Node* tail;
Node* head;
};
我的cpp文件
#include "LinkList.hpp"
LinkedChar::LinkedChar(std::string s)
{
int length = s.length();
Node* temp = new Node;
head = nullptr;
if(length==1)//If there is only one letter
{
temp->data=s[0];
head = temp;
tail = temp;
temp->next = nullptr;
std::cout<<temp->data;
}
else
{
for(int i = 1; i<length; i++)
temp->data = s[i];
temp->next = nullptr;
tail = temp;
}
}
解决方法
您是否正在编译.cpp文件?您的编译命令应类似于g++ -Iinclude/ main.cpp src/LinkedList.cpp
。
此外,请勿在.hpp文件中包含.cpp文件