我有两个文件,Book.h(头文件)和 Book.cpp。头文件包含我的 Book 类的函数头。我已将函数体放在我的 Book.cpp 文件中。
我只想编译 Book.cpp 文件。当我尝试这样做时,我遇到了很多错误,说`重载函数仅在返回类型上与 'type Book::functionName(void)
不同我已将头文件包含在我的 Book.cpp 文件中,如下所示。我不明白缺少什么。我在网上搜索过,但每个编译器似乎都以完全不同的方式处理将多个文件编译在一起。
注意:我还尝试添加另一个名为 menu.cpp 的 .cpp 文件,其中包含我的主文件。在这个 main 中,我只是尝试实例化一个 book 对象,但编译器无法识别我的 Book 类或它的任何成员函数....
Book.cpp 的内容如下:
#include "Book.h"
#include <string>
using namespace std;
static const int CHECK_OUT_LENGTH = 21;
Book::Book(){
idCode = "";
title = "";
author = "";
};
Book::Book(std::string idc, std::string t, std::string a){
idCode = idc;
title = t;
author = a;
};
int Book::getCheckOutLength(){
return CHECK_OUT_LENGTH;
};
std::string Book::getIdCode(){
return idCode;
};
std::string Book::getTitle(){
return title;
};
std::string Book::getAuthor(){
return author;
};
Locale Book::getLocation(){
return location;
};
void Book::setLocation(Locale lo){
location = lo;
};
Patron* Book::getCheckedOutBy(){
return checkedOutBy; //will return the address of the current patron who has checked out the book
};
void Book::setCheckedOutBy(Patron* p){
checkedOutBy = p; //will set the address of checkedOutBy pointer to the adress of the pointer p
};
Patron* Book::getRequestedBy(){
return requestedBy;
};
void Book::setRequestedBy(Patron* p){
requestedBy = p;
};
int Book::getDateCheckedOut(){
return dateCheckedOut;
};
void Book::setDateCheckedOut(int d){
dateCheckedOut = d;
};
这里是 Book.h 的内容:
#ifndef examples_Book_h
#define examples_Book_h
class Patron;
enum Locale {ON_SHELF, ON_HOLD, CHECKED_OUT};
class Book
{
private:
std::string idCode;
std::string title;
std::string author;
Locale location;
Patron* checkedOutBy;
Patron* requestedBy;
int dateCheckedOut;
public:
static const int CHECK_OUT_LENGTH = 21;
Book();
Book(std::string idc, std::string t, std::string a);
int getCheckOutLength();
std::string getIdCode();
std::string getTitle();
std::string getAuthor();
Locale getLocation();
void setLocation(Locale lo);
Patron* getCheckedOutBy();
void setCheckedOutBy(Patron* p);
Patron* getRequestedBy();
void setRequestedBy(Patron* p);
int getDateCheckedOut();
void setDateCheckedOut(int d);
};
#endif
以下是我的小主要功能的内容:
#include<iostream>
#include "Book.h" //why won't this work?
using namespace std;
int main(){
Book myBook;
return 0;
}
最佳答案
根据评论:在 header 中,确保所有使用的类型都已声明或定义,在本例中通过包含 .并且,确保可以找到包含的文件。
关于c++ - 在 Visual Studio 中为函数定义和头文件编译单独的 .cpp 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27207102/