读取文件并将其存储在C 中的保护变量中
Read file and store it in protected variable in c++
我正在尝试读取文件并将其存储在受保护变量中。所有方法都在同一类中。
class A: public B
{
public:
//method declarations
protected:
string d;
};
void A::l(std::string filename)
{
ifstream ifs;
ifs.open(filename);
string d { istreambuf_iterator<char> {ifs}, istreambuf_iterator<char> {} };
ifs.close();
}
void A::f(void)
{
std::cout << d.length() << std::endl;
}
当我尝试打印字符串的长度时,它是0。当我尝试在f()中打印 d
时,什么也不会打印。我需要 d
是一个受保护的变量,也不能更改方法。如何将读取文件字符串传递到f
方法?
您分配给本地,使用成员(this->
是可选的):
this->d.assign(istreambuf_iterator<char> {ifs}, {});
如果没有帮助,您可能会指定错误的文件名。
尝试一个绝对路径(例如/home/user/file.txt或c: documents user documents documents file.txt)>或检查程序的工作目录。
您可以随时检查错误:
if (!ifs) throw std::runtime_error("File could not be opened");
您的问题与您的变量受到保护无关。问题在于您正在定义另一个具有相同名称的变量。为了避免此问题,有些人将一个强调变量添加到变量的名称,例如" d_",其他人写下" m_d"。但是如果您不想,您就不需要这样做。
做您想做的一种方法是以下内容:
class A
{
public:
void l(std::string filename);
void f();
//method declarations
protected:
string d;
};
void A::l(std::string filename)
{
ifstream ifs{filename};
if(!ifs)
return; // error
std::copy(istreambuf_iterator<char>{ifs},
istreambuf_iterator<char>{},
std::back_inserter(d)); // this is A::d
}
您不需要使用'this->'。实际上,在C 中,您永远不会使用"此"(仅在诸如'return *this'之类的句子中)。
另外,在C 中,您不写:
void f(void);
但是,您写
void f();
,您也无需关闭ifstream。破坏者将为您做。
相关文章:
- 如何从其他结构访问受保护的结构变量
- 从模板化父类中的派生内部类访问受保护的成员变量
- 离开范围后如何保护局部变量的值?
- C++中的受保护变量
- 使用朋友函数时,会保护变量
- 如何影响派生类中受保护的基变量
- GCC 仍然使用 -fno-threadsafe-static 生成保护变量
- 读取文件并将其存储在C 中的保护变量中
- 虚函数在受保护变量上触发编译错误
- 为什么可以从派生实例访问基类中的受保护变量
- 继承中使用的受保护变量
- 有没有办法从类外部声明一个受保护C++变量?
- 访问派生类 C++ 中的受保护变量
- 保护C++变量不被溢出?如果值小于任何DataType的UpperBound
- 不继承的c++保护变量
- 受保护变量的命名和标准
- 重写派生类中的受保护变量
- 告诉子类对超类的受保护变量执行某些操作是否是一种好的做法(也许是一些已知的设计模式?)?
- 从类C访问类a中的受保护变量,其中C是B的子类,B是a的子类
- 如何访问子节点的受保护变量