您的位置:首页 > 编程语言 > C语言/C++

在类外定义的函数,被成员函数调用时,报运行时错误error LNK2005:已经在 classinfo.obj 中定义

2013-10-30 16:21 645 查看
问题描述:为了确定作用域的查找过程,在类体外定义了一个函数,当函数为普通函数时,被成员函数调用可以通过编译

            得出结论:查找函数声明的过程为,在成员函数实现之前,会先查找类定义,然后查找全局声明,即便全局声明在类体后声明,也可以被找到

但运行时则程序报错,将普通函数改为inline函数后,链接错误消失,没搞明白为什么,有知道的大牛可以给解释一下,先谢过了!

报错信息如下:

1>Person.obj : error LNK2005: "void __cdecl print(void)" (?print@@YAXXZ) 已经在 classinfo.obj 中定义

1>C:\Documents and Settings\user\桌面\classinfo\Debug\classinfo.exe : fatal error LNK1169: 找到一个或多个多重定义的符号

类定义头文件Person.h

#pragma once
#include <string>
#include <iostream>
using namespace std;
class Screen;

class Person
{
public:
explicit Person(void);
explicit Person(string s1, string s2):name(s1),address(s2){}
~Person(void);
string getName() const;
string getAddress() const;

Person& move(int len,int wid);
Person& set(string&str1);
Person& display(ostream&os);

public:
string address;
private:
string name;
int length;
int width;
};
//不加inline会报链接错误
inline void print(){
cout<<endl;
}


类实现cpp文件:Person.cpp

#include "StdAfx.h"
#include "Person.h"
#include <iostream>

Person::Person(void)
{
name	= "";
address = "";
length	= 0;
width	= 0;
}

Person::~Person(void)
{
}
string Person::getName() const
{
cout<<"The getName() return value is "<<name<<endl;
print();
return name;
}

string Person::getAddress() const
{
return address;
}

Person& Person::move(int len,int wid)
{
length	= len;
width	= wid;
return *this;
}

Person& Person::set(string&str1)
{
name = str1;
return *this;
}

Person& Person::display(ostream&os)
{
os << "The name is "	<<name	<<endl;
os << "The length is "	<<length<<endl;
os << "The width is "	<<width	<<endl;
return *this;
}


main函数classinfo.cpp

 

#include "Person.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{

Person per;
string setStr("Jinan");
per.move(10,5).set(setStr).display(cout).getName();
return 0;
}


 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ class
相关文章推荐