c++ - 为什么即使我使用新地址,我也总是生成相同的地址?
问题描述
我有这样的代码。
这是我的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++ 的初学者,我正在尝试理解指针和类。
解决方案
不要求 new 返回一个新地址。它所要做的就是返回一个不同于任何现有对象的地址。这就是它在你的程序中所做的。
s4
不同于s3
因为s3
在创建时仍然指向有效对象s4
。
s3
允许与创建时s2
没有s2
指向有效对象相同s3
。您delete s1;
在上一行中删除了该对象(因为s1
和s2
都指向同一个对象)。
换句话说,如果您每次都想要一个不同的地址,那么不要删除任何内容。
推荐阅读
- sql - SSRS LastStatus 可能值的综合列表
- recaptcha - Recaptcha 总是第一次遇到多个失败事件
- python - 将文本文件中的特定列制作成列表
- mocking - Spock 存根匹配部分参数
- python - 在 for 循环中更新 MySQL 表并同时从另一个 Python 文件中更新的 MySQL 表中提取此数据
- apache-beam - 如何在 Apache BEAM 中使用 withDynamicRead 和 KafkaIO
- c++ - 在映射中插入 thread::id 和类实例
- angular - SVG - 线性渐变 - 停止偏移/停止颜色属性 Angular
- logstash-grok - Grok 模式语义
- assembly - 使用 = 运算符或从文字池加载数据有什么区别?