【问题标题】:c++ Accessing variable from header vs in cpp filec ++从头文件与cpp文件中访问变量
【发布时间】:2013-12-05 11:56:02
【问题描述】:

所以我已经将很多变量(即字符串、整数、字符等)放入我正在创建的所有类的头文件中。我今天注意到的是,这样做时,当我尝试访问使用这些变量的方法时,我经常会得到堆栈转储。但是,如果我从头文件中删除变量并将其直接放入我的 cpp 文件中,它会很有效。我们只应该在 C++ 头文件中使用方法声明吗?如果不是,为什么会发生这种情况(所有变量都是私有的,但通过 set 和 get 方法访问)。

谢谢

在 main.cpp 中:

GameManager gamemngr;

GameManager.h

#include <string>
#include "Location.h"
#ifndef GAMEMANAGER_H_
#define GAMEMANAGER_H_

class GameManager {
public:
    GameManager();
    Location* curLoc;
    std::string gethelpMenu();
    void movePlayer(int i);
private:
    Location one, two;
    std::string helpMenu;
    void initialiseLocations();
};

#endif /* GAMEMANAGER_H_ */

位置.h

#include <string>
#ifndef LOCATION_H_
#define LOCATION_H_

class Location {
public:
    Location();
    void setEdges(Location *n, Location *e, Location *s, Location *w);
    Location* getEdge(int i);
    void setDescription(std::string s);
    std::string getDescription();
private:
    Location* pathways[];
    bool blocked[4];
    bool locked[4];

};

#endif /* LOCATION_H_ */

如果我将std::string description; 添加到位置标头,然后尝试通过curLoc-&gt;getDescription 访问它,它只会在到达程序中的该行时立即堆栈转储。我假设我的指针指向无效内存,但 curLoc 与对象“one”具有相同的内存地址。我是在错误地实例化我的对象还是什么?

编辑:我还将添加我确实在构造函数中将其设置为默认值,以确保字符串已正确初始化但没有效果。

位置实现(根据我的原始实现将描述放在头文件中):

#include "Location.h"
#include <string>
#include <iostream>

Location::Location() {
    description = "";
    for (int i = 0; i < 4; i++) {
        pathways[i] = NULL;
        blocked[i] = false;
        locked[i] = false;
    }
}

void Location::setEdges(Location *n, Location *e, Location *s, Location *w) {
    pathways[0] = n;
    pathways[1] = e;
    pathways[2] = s;
    pathways[3] = w;
}

Location* Location::getEdge(int i) {
    if(pathways[i] == NULL) {
        return this;
    } else {
        return pathways[i];
    }
}

void Location::setDescription(std::string s) {
        description = s;
}

std::string Location::getDescription() {
    return description;
}

我可能还应该添加这似乎只发生在我的描述字符串上,而不是我定义的边缘方法,据我所知它们正在工作(我需要描述来仔细检查我的指针位置可以肯定,但它不会堆栈转储或抛出错误)。

【问题讨论】:

  • 您能否举例说明您遇到的问题?
  • @nhgrif 添加了一些额外的信息,如果有帮助的话。
  • 如果您的意思是“我们是否只应该将方法声明放在 .cpp 文件中”,那么是的,您是。
  • stackoverflow.com/questions/18543980/… 可能是一个很好的阅读,链接器应该只看到一个具有特定名称的符号。你把它弄糊涂了,因为头文件定义了一个变量,它被包含的任何地方也定义了那个变量,所以链接器从你包含它的每个文件的编译对象中看到了大量的声明!
  • 转发声明...有人吗?

标签: c++ header


【解决方案1】:

存在编译器行为,如果编译器没有看到您的变量在 .cpp 文件中使用,那么它将从类中删除变量,除非有明确的编译标志告诉它不要这样做。您应该始终在 .cpp 文件中声明您的方法。

【讨论】:

  • “你应该总是在 .cpp 文件中声明你的方法”——谁说的?
  • @Jefffrey ".cxx" ftw,加号不稳定!他们倒下了!无论如何,您需要编译器来查看您的方法。有一个声明规则。
  • @Jefffrey stackoverflow.com/questions/18543980/… 这应该解释更多链接给你。一切都只能找到一个(除非它的链接很弱)
  • ...或者我想禁用这个优化
  • 我了解链接,也了解 ODR。我不知道是谁说你应该在.cpp 文件(源文件)中总是 声明你的方法(我认为你的意思是成员函数)。跨度>
猜你喜欢
  • 1970-01-01
  • 2016-07-29
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 2013-01-24
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
相关资源
最近更新 更多