Why would I encounter "Undefined symbols" after using friend function?

I'm trying to implement a string class, most features worked fine until I changed the operator+ from a member function to a friend function(in order to support operations like "123" + str).
My class header looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#ifndef MY_STRING_H
#define MY_STRING_H
namespace MyLib
{
	class string
	{
		public:
			string();
			string(const char[]);
			string(const string &);
			~string();
			string& operator=(const char[]);
			string& operator=(const string &);
			string& operator+=(const char[]);
			string& operator+=(const string &);
			friend const string operator+(const string &, const char[]);
			friend const string operator+(const char[], const string &);
			friend const string operator+(const string &, const string &);
			const bool operator==(const char[]) const;
			const bool operator==(const string &) const;
			const bool operator!=(const char[]) const;
			const bool operator!=(const string &) const;
			char& operator[](const int) const;
			const int length() const;
			char* c_str() const;
		private:
			char *str;
			unsigned int size;
	};
}
#endif 


And my implementation for operator+ are as follow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include"string.h"
#include<cstring>

//implementation for other functions, not shown here

const MyLib::string operator+(const MyLib::string &s, const char c_str[])
{
	MyLib::string res(s);
	return res += c_str;
}

const MyLib::string operator+(const char c_str[], const MyLib::string &s)
{
	MyLib::string res(s);
	return res += c_str;
}

const MyLib::string operator+(const MyLib::string &s1, const MyLib::string &s2)
{
	MyLib::string res(s1);
	return res += s2;
}

//implementation for other functions, not shown here 


As shown above, I have implemented all functions declared in my header, but the linker still reported an undefined symbol
Last edited on
As shown above, I have implemented all functions declared in my header, but the linker still reported an undefined symbol

You might help us out and let us know exactly what undefined symbol you're talking about.

Typically an object that is returned by value should be mutable, not const.
Place the overloaded operators in the namespace MyLib.
And remove the const qualifier from the return type.

1
2
3
// const MyLib::string operator+(const MyLib::string &s, const char c_str[])
MyLib::string MyLib::operator+( MyLib::string s, const char c_str[] ) // *** s is passed by value
{ return s += c_str ; }

Note: Favour the canonical form for overloading compound-assignment operators.
See: http://www.cplusplus.com/forum/general/152184/#msg791325
Last edited on
Thank you guys, I know the reason now
Topic archived. No new replies allowed.