在课堂上使用私有变量

时间:2012-09-24 08:09:41

标签: c++ class variables crash

如果我尝试引用我在其中一个类中创建的私有变量,我遇到了一个令人恼火的问题,我的程序一直在崩溃。我无法弄清楚我哪里出错了。这是调用崩溃类的类:

#include <stack>
#include <fstream>
#include <ostream>
#include <cstdlib>
#include <string>
#include <set>
#include "schemeList.cpp"

using namespace std;

class dataLog
{
public:
stack<string> commands;
set<string> domain;
processor tokens;
int nextToken;
schemeList * s;
dataLog(stack<string> s, ofstream * out, processor p, int location)
{
    commands = s;
    tokens = p;
    nextToken = location;
    commands.push("<Query List>");
    commands.push(":");
    commands.push("Queries");
    commands.push("<Rule List>");
    commands.push(":");
    commands.push("Rules");
    commands.push("<Fact List>");
    commands.push(":");
    commands.push("Facts");
    commands.push("<Scheme List>");
    commands.push(":");
    commands.push("Schemes");
    checkNext();
}

void checkNext()
{
    for(int i = 0; i < tokens.tags.size(); i++)
    {
        if(commands.top().compare(tokens.tags[i].getName())!=0)
        {
            if(commands.top().find("<")==0)
            {
                if(commands.top().compare("<Scheme List>")==0)
                {
                    int output = (*s).process(i, tokens, domain);                       string hi = (*s).toString();

                }
            }
        }
        commands.pop();
    }

}
};

这个类创建了一个SchemeList类的对象,该对象写成如下:

#include "schemes.cpp"
#include <cstdlib>
#include <string>
#include <set>
using namespace std;

class schemeList
{
private:
string success;

public:
int process(int number, processor p, set<string> domain)
{
    success = "HELLO";
    return 13;
}

string toString()
{
    return success;
}

};

当我到第15行success = "HELLO";时,程序崩溃并显示消息

Unhandled exception at 0x00E48B66 in lab2.exe: 0xC0000005: Access violation reading   
 location 0xCCCCCCE4.

我正在使用Microsoft Visual Studio Express 2012 for Windows Desktop。

3 个答案:

答案 0 :(得分:3)

首先,变量schemeList * dataLog::s永远不会被初始化,因此访问它是未定义的行为,这会导致崩溃。很可能在悬空指针上调用进程并尝试写入你不拥有的内存。

其次,不要#include "schemeList.cpp"。您不应该包含cpp个文件。相反,单独的声明&amp;实现并包含标题。

答案 1 :(得分:1)

您尚未初始化dataLog::s。当您致电(*s).process(i, tokens, domain)时,您会得到未定义的行为。

答案 2 :(得分:0)

首先,您显然在头文件中包含源代码文件。这可能会破坏一个定义规则,并且可能出现严重错误。

其次,'s'对于一个班级成员来说不是一个很好的名字。它几乎不可能找到它的用途。

第三,我可以看到你的代码中没有任何地方初始化s。我可以看到它被引用的位置OK,但由于它尚未初始化,因此取消引用的效果未定义,运气好的话只会使程序崩溃,这看起来就像正在发生的事情。

相关问题