![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
The Oblivious One
Join Date: May 2005
Location: Ontario, Canada
Posts: 648
Rep Power: 4
![]() |
friend functions causing trouble
Scripting languages make programming fun, but sometimes half the fun is working creating something yourself.
I was trying to make my own String class to get my C++ memory back. For some reason, when I try to invoke a function that I specifically made a friend, I get this error: $ g++ myString.cpp main.cpp -o string myString.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Jesse::String&)’: myString.h:9: error: ‘char* Jesse::String::str’ is private myString.cpp:13: error: within this context Which tells me that I am doing something wrong. The problem is that I have no idea what it is. Help would be appreciated. ![]() myString.h #include <iostream>
#ifndef MYSTRING_H_
#define MYSTRING_H_
namespace Jesse {
class String {
private:
char *str;
size_t size;
public:
String(const char *string);
friend std::ostream &operator<<(std::ostream &os, const Jesse::String &str);
size_t length() const;
virtual ~String();
};
}
#endifmyString.cpp #include "myString.h"
#include <cstring>
#include <iostream>
Jesse::String::String(const char *string)
: size(strlen(string)) {
str = new char[size];
strcpy(str, string);
}
std::ostream &operator<<(std::ostream &os, const Jesse::String &string) {
os << string.str;
return os;
}
size_t Jesse::String::length() const {
return size;
}
Jesse::String::~String() {
delete [] str;
}main.cpp #include "myString.h"
#include <iostream>
int main() {
Jesse::String str("Hello, world!");
std::cout << str;
return 0;
}Thanks ![]()
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS! |
|
|
|
|
|
#2 |
|
Professional Programmer
![]() Join Date: Sep 2005
Posts: 419
Rep Power: 4
![]() |
Wrap your implementation in the Jesse namespace too. Your problem isn't the friend function, it's a namespace scoping ambiguity:
#include "myString.h"
#include <cstring>
#include <iostream>
namespace Jesse {
String::String(const char *string)
: size(strlen(string)) {
str = new char[size];
strcpy(str, string);
}
std::ostream &operator<<(std::ostream &os, const String &string) {
os << string.str;
return os;
}
size_t String::length() const {
return size;
}
String::~String() {
delete [] str;
}
}
__________________
Even if the voices aren't real, they have some pretty good ideas. |
|
|
|
|
|
#3 |
|
The Oblivious One
Join Date: May 2005
Location: Ontario, Canada
Posts: 648
Rep Power: 4
![]() |
That fixed it. Thanks Narue!
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS! |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|