Reputation: 33
I'm having some troubles making a string utility class that has only static methods. Whenever I use a calling class to use a static method in my string utility class, it compiles with an LNK error, 2019. Any help would be much appreciated. .h is below,
#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 file is below,
#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;
}
and below is the calling class.
#include "stdafx.h"
#include <iostream>
#include "StringUtil.h"
void main()
{
cout << "Reversed String: " << StringUtil::Reverse("I like computers!");
}
And when it runs, it shows
Error 5 error LNK2019: unresolved external symbol "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) referenced in function "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++
and
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++
I feel like this is a very simple problem, but I'm used to programming in Java. I'm trying to teach myself how to code in c++ currently, hence my problem.
Upvotes: 3
Views: 4080
Reputation: 882
First of all in C++ we do not have static classes:
#pragma once
#include <string>
#include "stdafx.h"
#include <iostream>
using namespace std;
class StringUtil
{
public:
static string Reverse(string);
// bool Palindrome(string);
// string PigLatin(string);
// string ShortHand(string);
private:
// string CleanUp(string);
};
Second you forgot the class name StringUtil (owner):
string StringUtil::Reverse(string phrase)
{
string nphrase = "";
for(int i = phrase.length() - 1; i >= 0; i--)
{
nphrase += phrase[i];
}
return nphrase;
}
I hope this helps you :)
Upvotes: 5
Reputation: 206567
static string Reverse(string phrase)
{
...
}
does not define the static
member function of the class. It defines a file scoped non-member function. You need to use:
string StringUtil::Reverse(string phrase)
{
...
}
Upvotes: 0