c ++指针算术和类

时间:2015-07-24 04:27:35

标签: c++ pointers

所以我刚开始学习指针算法,我正在摆弄它的一些功能。一旦我开始尝试使用指针算法和类,我就遇到了问题。我在下面写了下面的代码:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;


class Cat
{
public:
    Cat();
    ~Cat();
    int GetAge() { return itsAge; }
    void SetAge(int age) { itsAge = age; }

private:
    int itsAge;

};

Cat::Cat()
{
}

Cat::~Cat()
{
}

int _tmain(int argc, _TCHAR* argv[])
{

    Cat *Family = new Cat[5];
    Family = Family + 1;
    Family->SetAge(3);
    cout << Family[1].GetAge()<< endl;

    return 0;
}

在我看来,我正在创建一个名为Family的指针,它将指向一个Cat对象数组。该指针将表示Family [0]的地址。然后,在下一行,我通过向指针本身添加1来指向系列指向新地址(因此编译器应该将此作为将地址槽向上移动到数组中的下一个元素,Family [1])。然后我将年龄设置为3并尝试输出Family [1]年龄的值,但我得到的答案是-842150451而不是3.我缺少什么?

5 个答案:

答案 0 :(得分:6)

未初始化itsAge,因为您尚未在默认构造函数中设置它。它目前是垃圾。

Cat::Cat()
: itsAge(0)
{
}

这成为一个问题,因为家庭[1]在您初始化之后指向Cat。指针[1]相当于*(指针+ 1)。

答案 1 :(得分:4)

我看到了几个问题:

  1. itsAge未在类的构造函数中初始化。将其更改为:

    Cat::Cat() : itsAge(0)
    {
    }
    
  2. 您对指针算术的理解存在轻微缺陷。

    你有:

    Cat *Family = new Cat[5];   // Family points to the first Cat
    Family = Family + 1;        // Now Family points to the second Cat
    Family->SetAge(3);          // Set the age of the second Cat
    
    cout << Family[1].GetAge()<< endl; // Since Family points to the
                                       // second object, Family[0] is the
                                       // second object. Family[1] is the third
                                       // object, not the second object.
                                       // That is the misunderstanding
    

答案 2 :(得分:2)

请注意,当你增加家庭时,

Family = Family + 1;

Family指向与Cat[1]对应的位置。现在,您使用:

设置Cat[1]的年龄
Family->SetAge(3);

但是在下一个声明中,您可以从Family [1]获得值指向Cat[2]实际

cout << Family[1].GetAge()<< endl;

因此,它打印垃圾,因为Family[1]等同于*(Family+1),即再次递增它。

相反,您可以使用 Family-&gt; GetAge()

Cat *Family = new Cat[5];   
Family = Family + 1; 
Family->SetAge(3);
cout << Family->GetAge()<< endl;

同时保持使用delete进行动态分配以防止内存泄漏的习惯。

答案 3 :(得分:1)

尝试:

function wlCommonInit(){    
    WL.Client.connect({onSuccess:success, onFailure:failure});
}

function success(response) {
    // ...
}

function failure(response) {
    if (response.getStatus() == "503") {
        // site is down for maintenance - display a proper message.
    } else if ...
}

答案 4 :(得分:1)

请参阅以下代码中的评论:

uasort
相关问题