2012-10-03 86 views
0

下午好。我從Visual c + +開始,我有一個編譯問題,我不明白。Visual C++錯誤LNK1120編譯

我得到的錯誤有以下幾種:

錯誤LNK1120外部鏈接懸而未決

錯誤LNK2019

我粘貼代碼:

C++ TestingConsole.CPP

#include "stdafx.h" 
#include "StringUtils.h" 
#include <iostream> 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
using namespace std; 
string res = StringUtils::GetProperSalute("Carlos").c_str(); 
cout << res; 
return 0; 
} 

StringUtils.cpp

#include "StdAfx.h" 
#include <stdio.h> 
#include <ostream> 
#include "StringUtils.h" 
#include <string> 
#include <sstream> 
using namespace std; 


static string GetProperSalute(string name) 
{ 
return "Hello" + name; 
} 

頁眉:StringUtils.h

#pragma once 
#include <string> 
using namespace std; 



class StringUtils 
{ 

public: 

static string GetProperSalute(string name); 

}; 

回答

2

你只需要聲明的類定義的方法static,並與類名來限定它,當你定義它:

static string GetProperSalute(string name) 
{ 
return "Hello" + name; 
} 

應該

string StringUtils::GetProperSalute(string name) 
{ 
return "Hello" + name; 
} 

其他說明:

  • 刪除using namespace std;。身高完全資格(例如std::string
  • StringUtils類好像它會更適合作爲namespace(這將意味着更多的對代碼的更改)
  • string res = StringUtils::GetProperSalute("Carlos").c_str();是沒用的,你可以這樣做:string res = StringUtils::GetProperSalute("Carlos");
  • 通字符串由const引用而不是按值:std::string GetProperSalute(std::string const& name)
+0

我剛剛發現它,當時它發佈了它的Luchian已經回答。謝謝老兄。 PD:爲什麼使用參考比價值更好?謝謝+ –

+0

@CarlosLande通過值創建一個額外的副本。從性能角度來看,它更好。 –