类中vector的作用域问题
Scope issue with vector inside class
#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
,因为words
是d
的成员。
在类中,每个成员(变量或函数)都属于对象。如果你有两个对象:
Dict d1("text1.txt");
Dict d2("text1.txt");
那么编译器没有办法理解words
,如果你的意思是d1
或d2
中的words
,除非你告诉它。你告诉它的方法是把对象名,后跟.
,然后是成员名。
即d1.words
和d2.words
是两个不同的向量
相关文章:
- C++quit()函数中可能存在作用域问题
- 作用域问题:如何从类外查看(不访问也不修改!)私有属性
- C++指针到指针作用域的问题
- 为什么编译器对此模板存在作用域问题
- 将对象的属性传递到方法时出现作用域问题.(opencv相关)
- 全局变量和枚举之间的作用域问题
- 遇到getline、fstream、作用域不一致的问题
- c++双删除文件作用域变量,链接问题
- 类中vector的作用域问题
- 模板作用域问题代码无法编译
- 构造函数排序(全局作用域)问题
- Make_shared在try catch作用域问题中
- c++作用域问题:创建一个矩阵类而不浪费空间
- 关于作用域的一般编程问题
- 当结构未解析为类型和作用域问题时的c++错误
- 名称空间和作用域可见性问题
- 关于从内存中释放链表的析构函数的逻辑和作用域的问题
- C++二进制树编程新节点离开作用域问题
- 在if语句if C++中创建对象时出现作用域问题
- 关于c++中作用域解析操作符的问题