我已经非常广泛地阅读了这两个错误,但尽管我付出了所有努力,但我在这里看不到问题所在。我已经完全用标题保护淹没了我的代码,看看这是否有帮助,结果没有改变。这是每个文件: Mystring.cpp
#pragma once
#include "MyString.h"
#ifndef MYSTRING_CPP
#define MYSTRING_CPP
using namespace std;
MyString::MyString(char chars[]){
str = (char*) malloc(strlen(chars));
str = chars;
}
//etc, other methods as defined in header file
#endif
我的字符串.h
#pragma once
#include <string.h>
#include <iostream>
#ifndef MYSTRING_H
#define MYSTRING_H
using namespace std;
class MyString {
protected:
char * str;
public:
~MyString();
MyString(char chars[]);
MyString(const char chars[]);
MyString();
int length();
void resize(int n, char c);
void clear();
bool empty();
void insert(int pos1, const MyString& str);
void insert (int pos1, const char* s);
void erase (int pos, int n);
int find(const MyString& str);
int find(const char* s);
int compare(const MyString& str);
int compare(const char* s);
const char* getStr() const;
MyString::MyString(const MyString &that);
MyString & operator=(const char chars[]);
MyString & operator=(const MyString& str);
};
#endif
MystringDerived.h
#pragma once
#include "MyString.cpp"
#ifndef MYSTRINGDERIVED_H
#define MYSTRINGDERIVED_H
class MyStringDerived :
public MyString
{
public:
MyStringDerived(char chars[]);
bool operator>(MyString rhs);
bool operator>=(MyString rhs);
bool operator<(MyString rhs);
bool operator<=(MyString rhs);
bool operator==(MyString rhs);
bool operator!=(MyString rhs);
bool operator+(MyString rhs);
bool operator[](MyString rhs);
MyStringDerived(void);
~MyStringDerived(void);
};
#endif
MyStringDerived.cpp
#pragma once
#include "MyStringDerived.h"
#ifndef MYSTRINGDERIVED_CPP
#define MYSTRINGDERIVED_CPP
MyStringDerived::MyStringDerived(char * const)
{
}
MyStringDerived::~MyStringDerived(void)
{
}
#endif
和我得到的错误
1>test.obj : error LNK2005: "public: int __thiscall MyString::length(void)" (?length@MyString@@QAEHXZ) already defined in MyString.obj
1>test.obj : error LNK2005: "public: void __thiscall MyString::resize(int,char)" (?resize@MyString@@QAEXHD@Z) already defined in MyString.obj
1>C:\Users\Arthur\Documents\Visual Studio 2012\Projects\Project1\Debug\Project2.exe : fatal error LNK1169: one or more multiply defined symbols found
有数百个错误行都看起来像这样。以我组织包含的方式,我绝对看不出我最终会如何包含多个副本。还有什么我想念的吗?任何见解都值得赞赏。这是作业(显然),所以当我在这里完成时,我肯定想真正理解问题。没有人向我展示过我做错了什么。
谢谢!
忘记包含 test.cpp。目前就这么简单:
MyStringDerived m = "测试"; cout<< m.getStr(); 获取字符();返回0;