如何使用C ++中的类对象作为函数参数 [英] How to use a class object in C++ as a function parameter

查看:652
本文介绍了如何使用C ++中的类对象作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何有一个接收类对象作为参数的函数。任何帮助?下面是一个例子。

 #include< iostream> 

void function(class object); // prototype

void function(class tempObject)
{
//使用对象执行操作
//使用或更改成员变量
}

基本上我只是困惑于如何创建一个函数,将接收一个类对象作为其参数,然后要在函数中使用这些参数,例如 tempObject.variable



对不起如果这有点混乱,对于C ++来说相对较新。

解决方案

class 仅用于*引入类定义。当你将新的类实例声明为局部对象或函数参数时,只使用类的名称(必须在范围内),而不是关键字 class 本身。 / p>

例如

  class ANewType 
{
// ... details
};

这定义了一个名为 ANewType 是类类型。



然后可以在函数声明中使用:

  void function(ANewType object); 

然后,您可以传递 ANewType 进入函数。该对象将被复制到函数参数中,所以,与基本类型非常相似,任何尝试修改参数将仅修改函数中的参数,并且不会影响最初传入的对象。



如果你想修改函数之外的对象,如函数体中的注释所示,你需要通过引用(或指针)获取对象。例如

  void function(ANewType& object); //通过引用传递的对象



此语法意味着任何使用 object 在函数体中引用的实际对象被传递到函数而不是副本。所有修改将修改此对象,并在函数完成后可见。



[* class 用于模板定义,但这是一个不同的主题。]


I am not sure how to have a function that receives a class object as a parameter. Any help? Here is an example below.

#include<iostream>

void function(class object); //prototype

void function(class tempObject)
{
   //do something with object
   //use or change member variables
}

Basically I am just confused on how to create a function that will receive a class object as its parameters, and then to use those parameters inside the function such as tempObject.variable.

Sorry if this is kind of confusing, I am relatively new to C++.

解决方案

class is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class itself.

e.g.

class ANewType
{
    // ... details
};

This defines a new type called ANewType which is a class type.

You can then use this in function declarations:

void function(ANewType object);

You can then pass objects of type ANewType into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.

If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.

void function(ANewType& object); // object passed by reference

This syntax means that any use of object in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.

[* The class keyword is also used in template definitions, but that's a different subject.]

这篇关于如何使用C ++中的类对象作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆