c++ - 如何通过函数(不在任何类中)在类中使用私有(private)变量?

标签 c++ class search stdvector friend

一个函数有 2 个参数。一种类型是类的 vector (有一个字符串私有(private)变量)。另一个是它寻找的字符串。我尝试了 == 两个字符串,但它不起作用。我期待它,但希望我可以在它上面使用 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 的私有(private)成员。这就是为什么我希望简单地使用一个 friend 就可以了。

最佳答案

Term 类的所有成员都在 private 监管之下,因此您甚至无法从中创建实例。你的老师肯定错过了/或者想让你弄明白这一点。

除了好友成员之外,您还可以提供一个 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_if std::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;
}

关于c++ - 如何通过函数(不在任何类中)在类中使用私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56267642/

相关文章:

c++ - 调试器在尝试跳出 C++11 std lib 时更深入

c++ - 技术上对象可以占用不连续的存储字节吗?

c++ - 引用绑定(bind)到类型为 'value_type' 的空指针

html - 什么类型的代码开始像这样的类 @media only screen and (max-width : 600px) { *[class ="NameOfClassHere"]

ios - 复制 Storyboard 时,界面生成器文件中的未知类

c++ - 指针数组的段错误

c++ - 在类构造函数中定义结构变量的参数

mysql - 我正在尝试使用通配符在 MySQL 中进行搜索和替换

django - Django haystack 和 whoosh 的字符折叠

php - 使用 laravel 按纬度和经度搜索