【问题标题】:Newb C++ Class ProblemNewb C++ 类问题
【发布时间】:2009-12-18 22:12:19
【问题描述】:

我正在尝试掌握指针及其出色之处以及更好的 C++ 理解。我不知道为什么这不会编译。请告诉我有什么问题吗?我试图在创建类的实例时初始化指针。如果我尝试使用普通的 int 它可以正常工作,但是当我尝试使用指针设置它时,我会在控制台中得到它

跑步……

构造函数调用

节目接收信号:“EXC_BAD_ACCESS”。

sharedlibrary apply-load-rules all

非常感谢任何帮助。

这里是代码

#include <iostream> 
using namespace std;
class Agents
{
public:
    Agents();
    ~Agents();
    int getTenure();
    void setTenure(int tenure);
private:
    int * itsTenure;
};
Agents::Agents()
{
    cout << "Constructor called \n";
    *itsTenure = 0;
}
Agents::~Agents()
{
    cout << "Destructor called \n";
}
int Agents::getTenure()
{
    return *itsTenure;
}
void Agents::setTenure(int tenure)
{
    *itsTenure = tenure;
}
int main()
{
    Agents wilson;
    cout << "This employees been here " << wilson.getTenure() << " years.\n";
    wilson.setTenure(5);
    cout << "My mistake they have been here " << wilson.getTenure() <<
             " years. Yep the class worked with pointers.\n";
    return 0;
}

【问题讨论】:

  • 它实际上可以编译,对吧?它在运行时崩溃。
  • 感谢大家的快速响应!
  • 作为参考,请记住,任何时候处理指针时,都需要在某处分配内存。如果你在堆栈上分配它,你可以使用一个指向你的局部变量的指针,直到你的方法返回,如果你在堆上分配它,你可以随意使用它,但记得在某个地方释放它。定义或传递指针永远不会分配它指向的对象。

标签: c++ pointers class


【解决方案1】:

您永远不会创建指针指向的 int,因此指针是指向不存在的内存区域的指针(或用于其他用途)。

可以使用new从堆中获取一块内存,new返回内存位置的地址。

itsTenure = new int;

所以现在itsTenure 保存了您可以取消引用它以设置其值的内存位置。

修改后的构造函数如下:

Agents::Agents()
{
    cout << "Constructor called \n";
    itsTenure = new int;
    *itsTenure = 0;
}

但你也必须记得使用delete删除它

Agents::~Agents()
{
    cout << "Destructor called \n";
    delete itsTenure;
}

【讨论】:

  • 不错的答案 (+1),但您的第二个代码块应该是析构函数而不是构造函数。
【解决方案2】:

您只是在构造函数中缺少一个新的。

 itsTenure = new int;

但是,您不需要将其设为指针。你为什么?

【讨论】:

    【解决方案3】:

    你必须为你的 int 分配一块内存,然后才使用这块内存的地址(指针)。这是通过new 完成的:

    cout << "Destructor called \n";   
    itsTenure = new int;    
    *itsTenure = 0;
    

    那么你必须用delete来释放析构函数中的内存:

        cout << "Destructor called \n";
        delete itsTenur;
    

    【讨论】:

      【解决方案4】:

      *itsTenure = 0 不初始化指针。它将 0 写入 itsTenure 指向的位置。由于您从未指定 itsTenure 指向的位置,因此它可能在任何地方并且行为未定义(最可能的结果是像您这样的访问冲突)。

      【讨论】:

        【解决方案5】:

        你需要在构造函数中为*tenure分配内存:

        Agents::Agents()
        {
            cout << "Constructor called \n";
            itsTenure = new int;
            *itsTenure = 0;
        }
        

        【讨论】:

          猜你喜欢
          • 2013-01-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-13
          相关资源
          最近更新 更多