未知函数已经存在错误
问题描述:
我有一个奇怪的错误,当我编译我的代码,它说,它确实另一个类中存在的成员函数alreadys不是错误说未知函数已经存在错误
错误LNK2005“市民:无效__thiscall membershipType: :打印(无效)” 在 personType.obj PROJECT1ç已经定义(打印@ @@ membershipType QAEXXZ):\用户\ okpal \源\回购\ PROJECT1 \ PROJECT1 \ Source.obj
和还
错误LNK1169一个或多个多重定义符号 发现PROJECT1 C:\用户\ okpal \源\回购\ PROJECT1 \调试\ PROJECT1.EXE 1
我想知道如果有人可以帮助找出错误 我的类代码如下
#include <iostream>
#include <string>
using namespace std;
class addressType { //class defintions and prototypes member variables
public:
addressType();
string streetAddressNum, streetName, streetType, city, stateInitials;
int zipCode;
};
class personType
{
public:
personType();
string firstName;
string lastName;
int personNum;
char gender;
int personID;
addressType address;
void setInterest1(string interest1);//mutator
void setInterest2(string interest2);
void printPerson();
string GetInterest1() const; // Accessor
string GetInterest2() const;
private:
string SetInterest1;
string SetInterest2;
};
//define membershipType class
class membershipType :public personType
{
public:
char membership_type;
char membership_status;
membershipType(); // 1st constructor
membershipType(char, char); // 2nd constructor
void print();
};
void membershipType::print()
{
cout << GetInterest1();
}
为persontype源代码
#include "personType.h"
personType::personType()
{
int personNum = 0;
int personID = 0;
}
addressType::addressType() {
int zipCode = 0;
}
void personType::setInterest1(string interest1) {
SetInterest1 = interest1;
}//mutator
void personType::setInterest2(string interest2) {
SetInterest2 = interest2;
}
string personType:: GetInterest1() const
{
return SetInterest1;
}// Accessor
string personType:: GetInterest2() const {
return SetInterest2;
}
void personType :: printPerson() {//constructor
cout << firstName << " " << lastName << " " << gender << " " <<
personID << " " << address.streetAddressNum << " "
<< address.streetName << " " << address.streetType
<< " " << address.city << " " << address.stateInitials
<< " " << address.zipCode << " " << SetInterest1 << " " << SetInterest2 << endl;
}
答
你有第一个代码块中的membershipType::print()
的定义,我认为这是从头文件复制的。在C++中,头文件的内容被插入到包含它们的每个文件中。据推测,你的程序中至少有两个源文件包含这个头文件。当这些源文件被编译为目标文件时,两者都将包含一个定义membershipType::print()
。当您尝试链接它们时,链接程序将检测到这两个文件都包含相同符号的定义。它不知道在哪里使用,所以它返回一个错误。
解决此问题的最简单方法是将membershipType::print()
的定义移动到源文件。你也可以通过内联来修复它。
将'print'的定义移动到实现文件(.cpp) –
好了,终于有效了,我想知道它为什么起作用了? –
阅读[odr](https://en.m.wikipedia.org/wiki/One_Definition_Rule) –