【问题标题】:How do I use a private variable in a class through a function(not in any class)?如何通过函数(不在任何类中)在类中使用私有变量?
【发布时间】:2019-05-23 03:18:29
【问题描述】:

一个函数有2 参数。一种类型是类的向量(具有字符串私有变量)。另一个是它要查找的字符串。我尝试了== 两个字符串,但它不起作用。我期待它,但希望我可以在上面使用friend,但它似乎只适用于2 类。

我尝试在 Term 类上使用 friend 函数进行搜索,但找不到使用一个类和一个函数的结果。除了friend,我想不出别的办法了。

class Term
{
    string str;
    unsigned long long int weight;
    Term(string s, long int w) : str(s), weight(w) {}
};
//my teacher provided this code so I can't change anything above

int FindFirstMatch(vector<Term> & records, string prefix)
//prefix is the word it looks for and returns the earliest time it appears.
{
    for (int i=0; i<records.size(); i++)
    {
        if (records[i].str==prefix)
        {
//I just need to get this part working
           return i;
        }
    }
}`

它说strTerm 的私有成员。这就是为什么我希望在上面简单地使用friend

【问题讨论】:

  • 您可以将FindFirstMatch 声明为友元函数,但您必须在类内部进行。如果你不能修改类,就没有办法做你想做的事。您确定您发布了老师提供的确切代码,并且您无法修改它吗?
  • Term 完全无法使用。没有什么是公开的,所以什么都不能访问。您甚至无法创建该类型的对象。必须在班级内声明朋友。声明要么缺少public: 作为第一行,要么需要是struct 而不是class

标签: c++ class search stdvector friend


【解决方案1】:

Term 类的所有成员都在private 监管下,因此您甚至无法从中创建实例。您的老师肯定错过了/或希望您弄清楚这一点。

除了friending 成员之外,您还可以提供一个 getter 函数来访问它。

class Term
{
private:
    std::string _str;
    unsigned long long int weight;

public:
    // constructor needs to be public in order to make an instance of the class
    Term(const std::string &s, long int w) : _str(s), weight(w) {}

    // provide a getter for member string
    const std::string& getString() const /* noexcept */ { return _str; }
};

int FindFirstMatch(const std::vector<Term>& records, const std::string &prefix)
{
    for (std::size_t i = 0; i < records.size(); i++)
    {
        if (records[i].getString() == prefix) // now you could access via getString()
        {
            return i;
        }
    }   
    return -1; // default return
}

或者如果您被允许使用 standard algorithms,例如使用 std::find_ifstd::distance

(See Live)

#include <iterator>
#include <algorithm>

int FindFirstMatch(const std::vector<Term>& records, const std::string &prefix)
{
    const auto iter = std::find_if(std::cbegin(records), std::cend(records), [&](const Term & term) { return term.getString() == prefix; });
    return iter != std::cend(records) ? std::distance(std::cbegin(records) , iter) : -1;
}

【讨论】:

  • 哦,非常感谢。你有什么技巧可以帮助你建立正确的心态吗?你只花了 10 分钟,包括写作,就弄明白了,而我花了几个小时,我还是想不通
  • @AbbasZaidi 如果您在学习时关注good books 中的任何一个,当然可以。
  • 感谢您提供链接并解释如何接受它。我以前从未使用过这个网站,事实证明我们可以在课堂上添加东西,这样你的例子就很好用了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-16
  • 2021-02-18
  • 2022-06-15
相关资源
最近更新 更多