C++ 如何在C++中使用类对象作为函数参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1896369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use a class object in C++ as a function parameter
提问by James
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
.
基本上,我只是对如何创建一个接收类对象作为其参数的函数感到困惑,然后在函数内部使用这些参数,例如tempObject.variable
.
Sorry if this is kind of confusing, I am relatively new to C++.
对不起,如果这有点令人困惑,我对 C++ 比较陌生。
回答by CB Bailey
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.
class
是一个关键字,仅用于* 引入类定义。当您将新类实例声明为本地对象或函数参数时,您只使用类的名称(必须在范围内)而不是关键字class
本身。
e.g.
例如
class ANewType
{
// ... details
};
This defines a new type called ANewType
which is a class type.
这定义了一个称为ANewType
类类型的新类型。
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 copiedinto 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.
然后,您可以将类型的对象传递ANewType
到函数中。该对象将被复制到函数参数中,因此,与基本类型非常相似,任何修改参数的尝试都只会修改函数中的参数,而不会影响最初传入的对象。
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.
这种语法意味着object
函数体中的任何使用都是指传递给函数的实际对象,而不是副本。所有修改都将修改此对象,并在功能完成后可见。
[* The class
keyword is also used in template definitions, but that's a different subject.]
[*class
关键字也用于模板定义中,但这是一个不同的主题。]
回答by James
At its simplest:
最简单的:
#include <iostream>
using namespace std;
class A {
public:
A( int x ) : n( x ){}
void print() { cout << n << endl; }
private:
int n;
};
void func( A p ) {
p.print();
}
int main () {
A a;
func ( a );
}
Of course, you should probably be using references to pass the object, but I suspect you haven't got to them yet.
当然,您可能应该使用引用来传递对象,但我怀疑您还没有使用它们。
回答by Barney
If you want to pass class instances(objects), you either use
如果你想传递类实例(对象),你要么使用
void function(const MyClass& object){
// do something with object
}
or
或者
void process(MyClass& object_to_be_changed){
// change member variables
}
On the other hand if you want to "pass" the classitself
另一方面,如果您想“通过”课程本身
template<class AnyClass>
void function_taking_class(){
// use static functions of AnyClass
AnyClass::count_instances();
// or create an object of AnyClass and use it
AnyClass object;
object.member = value;
}
// call it as
function_taking_class<MyClass>();
// or
function_taking_class<MyStruct>();
with
和
class MyClass{
int member;
//...
};
MyClass object1;
回答by vincent thorpe
I was asking the same too. Another solution is you could overload your method:
我也是这样问的。另一种解决方案是您可以重载您的方法:
void remove_id(EmployeeClass);
void remove_id(ProductClass);
void remove_id(DepartmentClass);
in the call the argument will fit accordingly the object you pass. but then you will have to repeat yourself
在调用中,参数将相应地适合您传递的对象。但你将不得不重复自己
void remove_id(EmployeeClass _obj) {
int saveId = _obj->id;
...
};
void remove_id(ProductClass _obj) {
int saveId = _obj->id;
...
};
void remove_id(DepartmentClass _obj) {
int saveId = _obj->id;
...
};
回答by geneemailbox1 geneemailbox1
holy errors The reason for the code below is to show how to not void main every function and not to type return; for functions...... instead push everything into the sediment for which is the print function prototype... if you need to use useful functions ... you will have to below..... (p.s. this below is for people overwhelmed by these object and T templates which allow different variable declaration types(such as float and char) to use the same passed by value in a user defined function)
神圣的错误 下面代码的原因是为了展示如何不使 main 每个函数都无效,而不是键入 return;对于函数......而不是将所有东西都推入沉淀物中,这是打印函数原型......如果你需要使用有用的函数......你将不得不在下面...... (ps下面是为了这些对象和 T 模板让人们不知所措,它们允许不同的变量声明类型(例如 float 和 char)在用户定义的函数中使用相同的值传递)
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
can anyone tell me why c++ made arrays into pass by value one at a time and the only way to eliminate spaces and punctuation is the use of string tokens. I couldn't get around the problem when i was trying to delete spaces for a palindrome...
谁能告诉我为什么 c++ 将数组一次传递一个值,而消除空格和标点符号的唯一方法是使用字符串标记。当我试图删除回文的空格时,我无法解决这个问题......
#include <iostream>
#include <iomanip>
using namespace std;
int getgrades(float[]);
int getaverage(float[], float);
int calculateletters(float[], float, float, float[]);
int printResults(float[], float, float, float[]);
int main()
{
int i;
float maxSize=3, size;
float lettergrades[5], numericgrades[100], average;
size=getgrades(numericgrades);
average = getaverage(numericgrades, size);
printResults(numericgrades, size, average, lettergrades);
return 0;
}
int getgrades(float a[])
{
int i, max=3;
for (i = 0; i <max; i++)
{
//ask use for input
cout << "\nPlease Enter grade " << i+1 << " : ";
cin >> a[i];
//makes sure that user enters a vlue between 0 and 100
if(a[i] < 0 || a[i] >100)
{
cout << "Wrong input. Please
enter a value between 0 and 100 only." << endl;
cout << "\nPlease Reenter grade " << i+1 << " : ";
cin >> a[i];
return i;
}
}
}
int getaverage(float a[], float n)
{
int i;
float sum = 0;
if (n == 0)
return 0;
for (i = 0; i < n; i++)
sum += a[i];
return sum / n;
}
int printResults(float a[], float n, float average, float letters[])
{
int i;
cout << "Index Number | input |
array values address in memory " << endl;
for (i = 0; i < 3; i++)
{
cout <<" "<< i<<" \t\t"<<setprecision(3)<<
a[i]<<"\t\t" << &a[i] << endl;
}
cout<<"The average of your grades is: "<<setprecision(3)<<average<<endl;
}