按理说指针类型应该还可以用指针的指针**接收,
或者使用指针的引用接收才对。
但是事实上我尝试使用另外两种方法接收实例化结果却失败了。。
MyClass *mc = new MyClass(11);
MyClass **mc = new MyClass(11); //错误
MyClass *&mc = new MyClass(11); //错误
我想问一下为什么这么做不行呢? 还是说我的写法有什么问题?
2016/8/9
感谢各位大大的回答, 第二条问题已解决 可改为
MyClass *mc = new MyClass(11);
MyClass **mmc = &mc;
补充说明:第三条问题语法检测是没错的,我的思路是用指针的引用接收,ide并没有错误提示,但是编译无法通过...
我改为采用第二种方式
MyClass *mc = new MyClass(11);
MyClass *&mmc = mc;
这样却没问题,为什么一开始new返回的指针无法用引用来处理呢?
还有。。 第二种方法直接&new的值会报错。。。有什么办法吗?
PHP中文网2017-04-17 14:29:35
For the third question, I directly replaced MyClass with int.
Because new int
returns an address, int& is an lvalue reference, and the address from new int is an rvalue, and the reference is an alias of an object or variable, but the address from new int is a constant address. It's equivalent to a number, such as 2 or 3, similar to int& a = 2
, which won't work. Using rvalue references compiles via int* &&a = new int(2)
.
高洛峰2017-04-17 14:29:35
The
types do not match. For example, MyClass **mc = new MyClass(11);
has a MyClass **
type on the left and a MyClass *
type on the right. How do I assign a value?
怪我咯2017-04-17 14:29:35
There is a problem with your understanding from the beginning.
1. C++ class instantiation generates pointers.
This is wrong! ! !
Generally speaking, it should be understood this way. In a C++ class, new creates an object and returns a pointer to the object.
2. So why can this pointer be received only with class *name?
MyClass *mc is:
Pointer to the object of the MyClass class.
new MyClass(11) returns a pointer, and the pointer type is:
Pointer to the object of the MyClass class.
The type of mc in MyClass **mc is:
Pointer to the pointer of the object of the MyClass class.
Can you compare the two data types?
In addition, I have never seen this way of writing MyClass *&mc. As I understand it, this is a grammatical error.
阿神2017-04-17 14:29:35
new MyClass(11); the return type is Myclass*, lvalue and rvalue types are different