代码之家  ›  专栏  ›  技术社区  ›  Cranium Slows

NeWB C++类问题

  •  1
  • Cranium Slows  · 技术社区  · 15 年前

    我试图了解指针和它们的惊人之处以及更好的C++理解。我不知道为什么这不会编译。请告诉我怎么了?我正在尝试在创建类的实例时初始化指针。如果我尝试使用一个普通的int,它可以很好地工作,但是当我尝试用一个指针设置它时,我会在控制台中得到这个

    跑步

    调用的构造函数

    程序接收信号:exc bad访问。

    共享库全部应用加载规则

    我们非常感谢您的帮助。

    这是密码

    #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;
    }
    
    5 回复  |  直到 15 年前
        1
  •  10
  •   Yacoby    15 年前

    您永远不会创建指针指向的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;
    }
    
        2
  •  4
  •   DanDan    15 年前

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

     itsTenure = new int;
    

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

        3
  •  3
  •   KeatsPeeks    15 年前

    必须为int分配一个内存块,然后才使用这个内存块的地址(指针)。这已经结束了 new :

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

    然后您必须使用delete释放析构函数中的内存:

        cout << "Destructor called \n";
        delete itsTenur;
    
        4
  •  3
  •   sepp2k    15 年前

    *itsTenure = 0 不初始化指针。它将0写入其保留期指向的位置。因为您从未指定它的保留期指向何处,所以它可能在任何地方,并且行为是未定义的(这是一种访问冲突,就像您得到的是最可能的结果一样)。

        5
  •  1
  •   florin    15 年前

    您需要在构造函数中为*保留期分配内存:

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