gpt4 book ai didi

c++ - 在 C++ 中创建公共(public)类

转载 作者:行者123 更新时间:2023-11-28 06:22:51 24 4
gpt4 key购买 nike

如果你不介意的话,我有一个小问题。

我开始学习如何使用类,但是当我尝试将程序的某个部分(要求用户输入要打开的文件名)变成一个函数并将其公开时,我遇到了一个问题。

在我原来的 main.cpp 文件中,我有这段代码,我试图向用户询问他或她想要打开的文件名:

    char in_filename[50];
ifstream infile;
cin.getline(in_filename, 50);
infile.open(in_filename);

if(!infile.is_open())
{
cout << "File cannot load."<< endl;
exit(EXIT_FAILURE);
}

int w, h;
string s;
infile >> s;
outfile <<s<<endl;
infile >> w;
outfile << w<<" ";
infile >> h;
outfile <<h<<endl;
infile >> s;
outfile <<s<<endl;

在我拥有所有函数的另一个名为 lib.cpp 的 .cpp 文件中,我尝试将代码转换为:

void PPMImage::GetFileName()
{
char in_filename[50];
ifstream infile;
cin.getline(in_filename, 50);
infile.open(in_filename);

if(!infile.is_open())
{
cout << "File cannot load."<< endl;
exit(EXIT_FAILURE);
}

}

在我的头文件中,我有:

class Image
{
public:
void GetFileName();
};

创建类后,我的新 main.cpp 是:

Image bo;   //create object
bo.GetFileName();

int w, h;
string s;
infile >> s;
outfile <<s<<endl;
infile >> w;
outfile << w<<" ";
infile >> h;
outfile <<h<<endl;
infile >> s;
outfile <<s<<endl;

但是,在运行代码后,我收到一条错误消息,指出“infile”未定义。这是因为 infile 是在 lib.cpp 中定义的,而 main.cpp 中的变量“infile”没有获取它,即使我之前调用了函数 bo.GetFileName?他们是固定的替代品吗?这些只是我的代码的一部分。这不是全部,但我觉得这是与此问题相关的唯一代码。欢迎任何意见/协助/建议。感谢您的支持!

最佳答案

在新的 main.cpp 中,infile 超出范围。它仅存在于 GetFileByName() 的实现中。此外,在你执行之后:

Image bo;   //create object
bo.GetFileName();

您已经创建了一个对象,并使用 bo.GetFileName(); 打开了一个 ifstream,但是您让 ifstream 打开而没有关闭它。你应该做的是

(1) 让 GetFileName() 返回 ifstream infile 以便您可以在 main.ccp 中访问它(并使用它执行输入操作)。看起来像这样:

Image bo;   //create object
ifstream infile = bo.GetFileName();

(2)(在我看来是首选)将 ifstream infile 声明为您的 Image 类的私有(private)成员,以便您可以实现允许输入的功能来自 ifstream

class Image {
public:
void GetFileName();
//methods to allow input operations from infile

private:
ifstream infile;
};

无论哪种方式,您都需要确保 ifstream 保持在范围内,并在程序终止之前使用 .close() 关闭!

关于c++ - 在 C++ 中创建公共(public)类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29046221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com