I'm trying to write a console application like Twitter. User and UserList classes including each other. I'm trying to access to following user's followers. UserList class is used for linked list.
//User.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
class UserList;
class User
{
friend class UserList;
private:
string userName;
string personalComment;
UserList *followed;
UserList *following;
int followedNumber;
int followingNumber;
//TWEET
UserList *blocked;
User* next;
public:
User();
User(string&,string&);
};
//UserList.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
class User;
class UserList{
private:
User *root;
public:
UserList();
~UserList();
void addUser(string&,string&);
bool checkUser(string&);
User& findUser(string&);
void printList();
};
Firstly, I wrote a function to find following user.
//userList.cpp
User& UserList::findUser(string& name)
{
User *temp=root;
while(temp!=NULL)
{
if(!name.compare(temp->userName))
{
return temp;
}
temp= temp->next;
}
temp= temp->next;
return temp;
}
For example user1 wants to follow user2. I want to check does user1 already follow user2.( checkUser(username) looks for a user in a list and return bool)
//main.cpp in main()
if(users.findUser(user1name).following->checkUser(user2name))
{
cout<<"Err: The user '"<< user1name << "' has already followed '"<<user2name<<"'!"<<endl;
}
But there is a "UserList* User::following is private" error and "within this context"
How can I access this user's lists?
In general you should not put logic of your classes in the main
. Your issue can be solved for example by adding a method to User
that tries to add another user instead of doing this in the main
. Something like this:
User::FollowOther(std::string other){
if(this->following->checkUser(other)) {
cout<<"Err: The user '"<< userName << "' has already followed '"<<other<<"'!"<<endl;
}
/*...*/
}
The error you got is because User::following
is private in User
. Private members can only be accessed from within the class. The exception is: You can access private members from within a different class that is declared as friend. But you cannot access private members in the main
. Btw, I am not at all a fan of declaring friends, because it breaks encapsulation and makes the relation between classes less obvious, but thats just my personal opinion.