什么是“使用”新" C ++中的运算符。 [英] what is use of " New" operator in C++.
本文介绍了什么是“使用”新" C ++中的运算符。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好
我是C ++的新手,请看下面的代码
Hi all
I am new to C++ can you please see code below
int main()
{
int *p;
*p=100; //line 4
cout<<* p;
}
输出:
1)如果我们可以直接给它确定new operator的用法。
2)由于指针只存储变量的地址,那么我们如何才能将变量赋值给它呢?
提前谢谢。
Output:
100
1) if we can assize it directly what is the use of "new operator" then.
2)As pointer just store a address of variable then how can we assize a variable to that?
Thanks in advance .
推荐答案
除非你使用的是一个非常糟糕的编译器,否则它会胜利你说的是:在编译时初始化之前会出现p的警告,执行时会出现运行时错误到同样的效果,然后是你正在访问内存的第二次运行时错误你不应该继续。
既然你没有在任何时候给p赋值,它将保持为零 - 并且记忆在该位置不属于您,它受到保护,您无法读取或写入。
如果您这样做,您将获得有效的结果:
Unless you are using a spectacularly poor compiler that won;t do what you say: you will get a warning that "p" is being used before it is initialised when you compile, and a run time error to the same effect when you execute, followed by a second run time error that you are accessing memory that you shouldn't if you continue anyway.
Since you don't assign a value to "p" at any point, it will remain at zero - and memory at that location is not yours, it's protected and you can't read or write to it.
You would get a valid result if you did this:
int *p;
p=(int*)100;
cout<< p;
但这不会打印100:它会打印00000064,因为默认情况下指针会打印为十六进制值。
But that wouldn't print "100": it would print "00000064" because pointers are printed as hexadecimal values by default.
参见 http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx [ ^ ]。
这篇关于什么是“使用”新" C ++中的运算符。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文