【发布时间】:2012-09-01 19:20:53
【问题描述】:
我是 C++ 编程的新手,我从我设置的 char* 变量返回一个奇怪的值,这取决于我如何使用它。我显然在做一些非常愚蠢的事情,但我看不到问题所在。接下来的几段描述了设置(很糟糕),但只看输出和代码可能更容易。
基本上,我有几个类 - Menu 和 MenuItem。 MenuItem 类有一个 char* 类型的名称。根据我使用菜单项的方式,当我在 MenuItems 上执行 getName() 时会得到奇怪的结果。
我有一个具有状态 (TestState) 的 Machine 类。此 TestState 创建一个包含 MenuItems 的菜单。当我在我的主函数中创建一个 TestState 并让它打印出菜单时,我得到了我所期望的。当我创建一个包含 TestState 的机器并要求它打印菜单时,它会为菜单中的根项目的名称打印一些奇怪的东西。
输出 - 最后一行我期待 menuItem1,但我得到 HâΔHã=ò
Output direct from TestState Object
Displaying menu state
menuItem1
root not null
menuItem1
Output from TestState within Machine
Displaying menu state
menuItem1
root not null
Hâ∆Hã=ò
这是我的代码 - Main.cpp
#include "Menu.h"
#include "Machine.h"
#include <iostream>
using namespace std;
Machine m;
TestState t;
int main(void) {
cout << "Output direct from TestState Object" << endl << endl;
t = TestState();
t.print();
cout << endl << endl << "Output from TestState within Machine" << endl << endl;
m = Machine();
m.printCurrentState();
}
Menu.h
#ifndef Menu_h
#define Menu_h
#include <stdlib.h>
class MenuItem {
public:
MenuItem();
MenuItem(const char* itemName);
const char* getName() const ;
protected:
MenuItem *next;
const char* name;
};
class Menu {
public:
Menu(MenuItem *rootItem);
Menu();
void setRoot(MenuItem *r);
MenuItem* getRoot() ;
protected:
MenuItem *root;
};
#endif
Machine.h
#ifndef MACHINE_H_
#define MACHINE_H_
#include "Menu.h"
class TestState;
class Machine;
class TestState {
public:
TestState();
virtual ~TestState();
void print();
protected:
Machine* machine;
MenuItem menuItem1;
Menu menuMain;
};
class Machine {
public:
Machine();
void printCurrentState();
protected:
TestState testState;
};
#endif /* MACHINE_H_ */
Machine.cpp
#include "Machine.h"
#include <iostream>
using namespace std;
TestState::TestState() {
menuItem1 = MenuItem("menuItem1");
menuMain = Menu(&menuItem1);
}
void TestState::print(){
cout << "Displaying menu state " << endl;
cout << menuItem1.getName() << endl;
if (menuMain.getRoot() == NULL) {
cout << "root is null" << endl;
} else {
cout << "root not null " << endl;
cout << menuMain.getRoot()->getName() << endl;
}
}
TestState::~TestState() {
// TODO Auto-generated destructor stub
}
Machine::Machine() {
testState = TestState();
}
void Machine::printCurrentState() {
testState.print();
}
任何帮助将不胜感激。我有点失落。 谢谢 戴夫
【问题讨论】:
-
这不可能是解决问题所需的最少代码量。另外,为什么要同时包含
和 ? -
在发帖之前,您确实应该自己缩小问题范围。这是很多代码要经过。
-
@oldrinb:并不是每个人都在使用 C++11 编译器。
NULL工作得很好。nullptr只是消除了边缘情况下的一些潜在错误。 -
Wug - 对包含的公平评论 - 不需要 stdio.h。至于代码量 - 我已经剥离了原始 Machine 类以减少我的代码量,而 TestState 只是 Machine 可能处于的多种可能状态之一。这些类在这种精简的状态,但它们运行,并证明了我遇到的问题 - 除非我忘记了什么:)
-
pmr - 我尽量缩小范围,同时仍然包含我认为必要的所有代码。我知道这很多,但我认为最好包括太多而不是留下空白。不过,我想我在描述问题方面做得并不好。