【发布时间】:2017-05-09 16:17:36
【问题描述】:
我在创建一个只有静态方法的字符串实用程序类时遇到了一些麻烦。每当我在我的字符串实用程序类中使用调用类来使用静态方法时,它都会编译并出现 LNK 错误,2019。任何帮助将不胜感激。 .h 在下面,
#pragma once
#include <string>
#include "stdafx.h"
#include <iostream>
using namespace std;
static class StringUtil
{
public:
static string Reverse(string);
// bool Palindrome(string);
// string PigLatin(string);
// string ShortHand(string);
private:
// string CleanUp(string);
};
.cpp 文件在下面,
#include "StdAfx.h"
#include "StringUtil.h"
#include <iostream>
static string Reverse(string phrase)
{
string nphrase = "";
for(int i = phrase.length() - 1; i > 0; i--)
{
nphrase += phrase[i];
}
return nphrase;
}
下面是调用类。
#include "stdafx.h"
#include <iostream>
#include "StringUtil.h"
void main()
{
cout << "Reversed String: " << StringUtil::Reverse("I like computers!");
}
当它运行时,它会显示
错误 5 错误 LNK2019: 无法解析的外部符号“public: static class std::basic_string,class std::allocator > __cdecl StringUtil::Reverse(class std::basic_string,class std::allocator >)” (?Reverse @StringUtil@@SA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V23@@Z) 在函数“void __cdecl a10_StringUtil(void)”中引用(?a10_StringUtil@@YAXXZ) H:\Visual Studio 2010\Projects\Object Oriented C++\Object Oriented C++\Object Oriented C++.obj Object Oriented C++
和
Error 6 error LNK1120: 1 unresolved externals H:\Visual Studio 2010\Projects\Object Oriented C++\Debug\Object Oriented C++.exe 1 1 Object Oriented C++
我觉得这是一个非常简单的问题,但我习惯用 Java 编程。我目前正在尝试自学如何用 C++ 编写代码,因此我遇到了问题。
【问题讨论】:
-
static string Reverse(string phrase)-->static string StringUtil::Reverse(string phrase) -
但我习惯用 Java 编程 -- 不要使用 Java 作为编写 C++ 代码的模型 -- 它们不是同一种语言。
static class StringUtil-- 不需要static class,只需class。 -
这个类在 C++ 中完全没有必要——你可以只使用函数。学习无类编程,解放自己。
-
欢迎。请注意,没有必要在问题标题中包含“已解决”,因为我们可以看到(甚至在网站的其他地方)您已经接受了答案。