2013-04-04 14 views
1

我得到了下面的代码:C++的Visual Studio 2010 LNK2019错误 - 是需要一些基本的建议

FooClass.h 

#pragma once 

#include <string> 
#include "StdAfx.h" 
#include "FooClass.h" 

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

FooClass::FooClass(void) 
{ 
} 


FooClass::~FooClass(void) 
{ 
} 


int PrintMsg (std::string msg) 
{ 
    printf ("%s\n", msg); 
    return 1; 
} 

class FooClass 
{ 
public: 
    FooClass(void); 
    ~FooClass(void); 

    static int PrintMsg (std::string msg); 
}; 

FooClass.cpp 


CODETESTER.cpp 

// CODETESTER.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 

#include "FooClass.h" 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    FooClass::PrintMsg ("Hi World!!"); 

    return 0; 
} 

bulding的时候该项目I'm收到以下错误:

Erro 4 error LNK2019: símbolo externo indefinido "public: static int __cdecl FooClass::PrintMsg(class std::basic_string,class std::allocator >)" ([email protected]@@[email protected][email protected]@[email protected]@[email protected]@[email protected]@[email protected]@@Z) referenciado na função _wmain E:\2. MEZASOFT\DESENVOLVIMENTO\PROTOTIPOS\CODETESTER\CODETESTER\CODETESTER.obj CODETESTER

从来就阅读关于这个主题的几篇文章,以及帮助,但没有找到如何修正它。

我知道.h不足以让链接器知道PrintMsg代码在哪里,但是 - 我该如何解决它。

对不起,如果这是一个基本问题。很久以前,我曾经是一名优秀的C程序员。我将以C++程序员的身份回来。

回答

2

您为FooClass声明了PrintMsg函数,但您从未定义/实现它。相反,您定义了一个函数PrintMsg,它并不与FooClass关联。

要正确实现PrintMsg功能FooClass:

int FooClass::printMsg(std::string msg) 
{ 
    printf("%s\n", msg.c_str()); 
    return 1; 
} 

作为一个侧面说明,你应该通过引用传递参数味精。这样,每次printMsg被调用时,字符串对象都不会被复制。

// you'll also need to change the printMsg declaration inside the FooClass 
int FooClass::printMsg(const std::string &msg) 
{ 
    printf("%s\n", msg.c_str()); 
    return 1; 
} 
+0

Ops ...基本...感谢您的回答... – Cox 2013-04-04 00:57:19

+0

顺便说一句:该功能不打印“嗨世界!!”但在屏幕上的垃圾。在这两个实现中... – Cox 2013-04-04 00:58:21

+0

编辑所以字符串打印出来(需要添加调用'c_str()') – helloworld922 2013-04-04 01:09:10