类中vector的作用域问题

Scope issue with vector inside class

本文关键字:问题 作用域 vector 类中      更新时间:2023-10-16
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
class Dict
{
public:
    string line;
    int wordcount;
    string word;
    vector<string> words;
    Dict(string f)
    {
        ifstream myFile;
        myFile.open(f.c_str());
        if (myFile.is_open())
        {
            while(!myFile.eof())
            {
                myFile >> word;
                words.push_back(word);
            }
            cout << endl << "Wordcount: " << wordcount << endl;
        }
        else
            cout << "ERROR couldn't open file" << endl;
        myFile.close();
    }
};
int main()
{
    Dict d("test.txt");
    cout << words.size() << endl;
    return 0;
}

我得到一个错误,没有在main()中声明words vector。

我如何使它对编译器可见,因为我已经在类中定义了它。一旦对象实例化并调用构造函数,不应该创建单词vector吗?但是编译器不会注意到这个

我该如何解决这个问题?

words是您的Dict对象d:

int main() {
    Dict d("test.txt");
    cout << d.words.size();
    return 0;
}

既然您可以有这个类的几个对象,每个对象都有自己的words实例,那么编译器应该如何知道您指的是哪个对象?

告诉编译器在哪里可以找到这些单词:

cout << d.words.size();

应该使用d.words,因为wordsd的成员。

在类中,每个成员(变量或函数)都属于对象。如果你有两个对象:

Dict d1("text1.txt");
Dict d2("text1.txt");

那么编译器没有办法理解words,如果你的意思是d1d2中的words,除非你告诉它。你告诉它的方法是把对象名,后跟.,然后是成员名。

d1.wordsd2.words是两个不同的向量