是否将类对象视为值类型

是否将类对象视为值类型

本文介绍了如果不使用new运算符进行初始化,C ++是否将类对象视为值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

示例代码:

MyItemType a;
MyItemType b;
a.someNumber = 5;
b = a;

cout << a.someNumber << endl;
cout << b.someNumber << endl;

b.someNumber = 10;

cout << a.someNumber << endl;
cout << b.someNumber << endl;

输出:

5
5
5
10

如果a和b是引用类型,则最后两行应该是10和10,而不是我猜的5和10.

If a and b were reference types, the last 2 lines would have been 10 and 10 instead of 5 and 10 I guess.

这是否意味着您进行如下声明:

Does this mean when you do a declaration like this:

AClassType anInstance;

它被视为值类型吗?

------这里是MyItemType.h ------------

------Here is MyItemType.h------------

#ifndef MYITEMTYPE_H
#define MYITEMTYPE_H

class MyItemType{

public:
    int someNumber;
    MyItemType();
};

MyItemType::MyItemType(){
}

#endif  /* MYITEMTYPE_H */

推荐答案

实际上,它不是像值类型那样对待.

It is not treated like a value type, in fact it is.

尽管在Java对象变量中存储了对对象的引用,但在C ++中,对象与其引用之间存在重要区别.默认情况下,分配实际上是按值分配的.

While in Java object variables store references to objects, in C++ there is an important difference between an object and its reference. Assignment is by default really by value.

如果希望变量只是一个引用,则可以使用引用或指针类型,具体取决于要使用的变量.这些类型声明为T*T&.

If you want a variable to be just a reference, you use either a reference or a pointer type, depending what you want to with it. These types are declared T* and T&.

为了进一步说明这一点:

To illustrate this a little more:

在Java中,当您说MyClass obj时,会创建一个对象,但是引用/指针存储在变量obj中.

In Java, when you say MyClass obj, an object is created, but a reference/pointer is stored in the variable obj.

在C ++中,MyClass obj创建对象并将其存储在obj中.如果要使用引用/指针,则需要将变量明确声明为MyClass* objPointerMyClass& objReference.

In C++, MyClass obj creates the object and will stored it in obj. If you want to work with references/pointers, you need to declare variables explicity as MyClass* objPointer or MyClass& objReference.

这篇关于如果不使用new运算符进行初始化,C ++是否将类对象视为值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:56