首页 > 解决方案 > 为什么即使我使用新地址,我也总是生成相同的地址?

问题描述

我有这样的代码。

这是我的Sayi课,

class Sayi{
    private:
            int deger;
    public:
            Sayi(): deger(0){}
            Sayi(int dgr): deger(dgr){}
            int Deger() {return deger;}
};

这是我的主要内容,

int main(){

    Sayi *s1, *s2;
    s1= new Sayi(50);
    s2=s1;

    delete s1;

    Sayi *s3= new Sayi(220);
    Sayi *s4= new Sayi(235);

    std:: cout<< "address of s1: " << s1 << std::endl;
    std:: cout<< "address of s2: " << s2 << std::endl;
    std:: cout<< "address of s3: " << s3 << std::endl;
    std:: cout<< "address of s4: " << s4 << std::endl;

    std:: cout<< "Value of s2: "<< s2->Deger() << std::endl;
    std:: cout<< "Value of s3: "<< s3->Deger() << std::endl;
    std:: cout<< "Value of s4: "<< s4->Deger() << std::endl;

    return 0;
}

我有这样的输入,

address of s1: 0x55db4dc04eb0
address of s2: 0x55db4dc04eb0
address of s3: 0x55db4dc04eb0
address of s4: 0x55db4dc04ed0
Value of s2: 220
Value of s3: 220
Value of s4: 235

这是我的问题。为什么所有地址都相等?为什么我不能用 new 创建一个新地址,为什么 s2 和 s3 彼此相等而 s4 不同?我希望 s2=50 但 s2=220 为什么会这样?对不起,如果问题很愚蠢并且错字。我是 C++ 的初学者,我正在尝试理解指针和类。

标签: c++

解决方案


不要求 new 返回一个新地址。它所要做的就是返回一个不同于任何现有对象的地址。这就是它在你的程序中所做的。

s4不同于s3因为s3在创建时仍然指向有效对象s4

s3允许与创建时s2没有s2指向有效对象相同s3。您delete s1;在上一行中删除了该对象(因为s1s2都指向同一个对象)。

换句话说,如果您每次都想要一个不同的地址,那么不要删除任何内容。


推荐阅读