0

我正在开发一个需要将数据存储在文件中的 MFC 应用程序

我有这样的课

class Client
{
public:
    Client(CString Name , CString LastName , CString Id );
    int create();
    int update(Client & myClient);

    CString name;
    CString lastName;
    CString id;
};



Client::Client(CString Name , CString LastName , CString Id )
{
    name = Name;
    lastName=LastName;
    id=Id;
}

void displayMessage(CString message , CString title=L"Meesage")
{
    MessageBox(NULL,message,title,MB_OK | MB_ICONERROR);
}


    int Client::create(Client myClient)
    {
        ofstream output;
        output.open("test.dat" , ios::binary );
        if( output.fail() )
        {
            CString mess;
            mess = strerror( errno );
            displayMessage(mess);
            return 1 ;//anything but 0
        }


        output.write( (char *) &myClient , sizeof(Client));
        output.close();

        return 0;
    }


    int Client::update(Client & myClient)
    //also tried passing by value : int update(Client myClient)
    {
        ifstream input;
        input.open("test.dat" , ios::binary );
        if( input.fail() )
        {
            CString mess;
            mess = strerror( errno );
            displayMessage(mess);
            return 1 ;//anything but 0
        }


        input.read( (char *) &myClient , sizeof(Client));
        input.close();

        return 0;
    }

创建功能效果很好,

但是,关于更新功能我有一些问题

我使用这样的功能:

Client myClient();
myClient.update(myClient);

但是当我运行这个函数时我得到了这个错误

 Unhandled exception at 0x5adfab2a (mfc100ud.dll) in MyProject.exe: 0xC0000005: Access violation writing location 0x039708fc.

我能做些什么?

4

2 回答 2

2

小心。Client myClient(); 声明一个名为myClient. 写入函数的地址会导致一些问题,比如崩溃。只需将其更改为Client myClient;(这样您就可以创建一个实际的Client对象,然后实际写入一个对象)。当然,我希望写入这样的Client对象是安全的(例如,参见 Joachim Pileborg 关于指针的评论)。

例如,看下面的代码:

#include <typeinfo>
#include <iostream>

struct S {};

int main()
{
    S s1();
    S s2;
    std::cout << typeid(s1).name() << std::endl;
    std::cout << typeid(s2).name() << std::endl;
}

结果(使用 g++)打印出来:

F1SvE
1S

重要的一点是它们不一样!s1是一个名为的函数的声明s1,它不带参数并返回一个S. s2是一个实际的S对象。这被称为 C++ 的“最令人烦恼的解析”(因为它会导致很多挫败感)。

编辑:哦,男孩,您不断用更多(实际)代码更新您的问题,并且不断改变事情。为了将来参考,只需从完整的实际代码开始,这样人们就不必不断改变事情:)

你不能CString像那样安全地写 s 。它们在内部存储指针,就像 Joachim Pileborg 提到的那样,在尝试读取它们时会造成严重破坏。

此外,Client不再有默认构造函数(因为您已经提供了自己的构造函数)。所以你也不能再说Client myClient;了。您必须使用正确的构造函数。

于 2013-01-19T15:54:07.587 回答
0

您不能将 CString 内容存储为二进制数据。您必须使用fprintf,CStdioFile::WriteString或类似的东西来写入数据。CString 没有固定大小的缓冲区,因此地址是无效的。

我的建议是将学习问题分解为几个部分——实践CString、文件 io、类设计和 UI 作为不同的方面。除非您对其他方面感到满意,否则不要将它们全部混合。你不会知道问题出在哪里。

此外,您发布的代码明显错误:create方法在类中没有任何参数,但在实现时您有一个参数!

于 2013-01-20T04:41:54.537 回答