【问题标题】:Access friend class's private member访问朋友班级的私人成员
【发布时间】:2015-11-25 19:32:13
【问题描述】:

我正在尝试编写一个控制台应用程序,例如 Twitter。 User 和 UserList 类包括彼此。我正在尝试访问以下用户的关注者。 UserList 类用于链表。

//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();
};

首先,我写了一个函数来查找关注用户。

//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;
}

例如 user1 想关注 user2。我想检查 user1 是否已经关注 user2。( checkUser(username) 在列表中查找用户并返回 bool)

//main.cpp in main()
if(users.findUser(user1name).following->checkUser(user2name))
{
            cout<<"Err: The user '"<< user1name << "' has already followed '"<<user2name<<"'!"<<endl;
} 

但存在“UserList* User::following is private”错误和“在此上下文中”

如何访问该用户的列表?

【问题讨论】:

  • twitter 是一个控制台应用程序?
  • @tobi303 想的完全一样。 :P 显然有些人不使用 HTML 渲染器,而只是阅读标签和所有内容......
  • 您的代码中没有User::followed
  • 这里没有看到任何嵌套类,class User里面没有类声明或定义。
  • @MervePia UserList 在哪里嵌套在 User 中?

标签: c++ linked-list singly-linked-list nested-class


【解决方案1】:

一般来说,您不应将类的逻辑放在main 中。例如,可以通过向User 添加一个方法来解决您的问题,该方法尝试添加另一个用户,而不是在main 中执行此操作。像这样的:

User::FollowOther(std::string other){
    if(this->following->checkUser(other)) {
        cout<<"Err: The user '"<< userName << "' has already followed '"<<other<<"'!"<<endl;
    }
    /*...*/
} 

您得到的错误是因为User::followingUser 中是私有的。私有成员只能从类内部访问。例外情况是:您可以从声明为朋友的不同类中访问私有成员。但是您无法访问main 中的私人成员。顺便说一句,我根本不喜欢声明朋友,因为它破坏了封装并使类之间的关系不那么明显,但这只是我个人的看法。

【讨论】:

  • 哦,我明白了!我正在尝试
  • @MervePia 您的代码还有其他一些小问题,例如为什么要存储指向列表的指针?我认为没有必要这样做。还有一件小事:让followedNumberfollowingNumber 成为User 的成员会迫使您编写不必要的代码,因为您必须使这些数字保持最新。而是为 UserList 提供一个 size() 方法,以达到相同的目的。
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
  • 1970-01-01
  • 2019-08-28
相关资源
最近更新 更多