C++ 更改函数中类实例的值

C++ 更改函数中类实例的值,c++,oop,C++,Oop,我编写了以下代码来测试如何更改函数中类对象的值 using namespace std; class test{ public: int a; }; void runer(test testXX){ testXX.a=10; } int main() { test test1; test1.a=5; runer(test1); cout<<test1.a; return 0; } 使用名称空间std; 课堂测试{ 公众:

我编写了以下代码来测试如何更改函数中类对象的值

using namespace std;

class test{
public:
    int a;
};

void runer(test testXX){
    testXX.a=10;
}

int main()
{
    test test1;
    test1.a=5;
    runer(test1);
    cout<<test1.a;
    return 0;
}
使用名称空间std;
课堂测试{
公众:
INTA;
};
无效运行器(测试testXX){
testXX.a=10;
}
int main()
{
测试1;
试验1.a=5;
runer(test1);
库特
获取类型
test
的完整副本,因此它在函数中被修改,但与main中的实例不同

C++
中的参数是按值发送的

 int function( int value ) {
      for( ; value > 0 ; value-- ){
          cout << "Hello\n";
      }
 } 

 int main( int , char ** ){
       int value = 10;
        function( value ); // display 10 things
        function( value ); // display 10 things again (not modified).
        function( 5 );  // also not making sense, if parameter is modified.
 }
现在,相同的对象从main发送到
runner
,并对单个对象进行修改

获取类型
test
的完整副本,因此它在函数中被修改,但与main中的实例不同

C++
中的参数是按值发送的

 int function( int value ) {
      for( ; value > 0 ; value-- ){
          cout << "Hello\n";
      }
 } 

 int main( int , char ** ){
       int value = 10;
        function( value ); // display 10 things
        function( value ); // display 10 things again (not modified).
        function( 5 );  // also not making sense, if parameter is modified.
 }

现在,同一个对象从main发送到
runner
,并对单个对象进行修改。

您通过值将参数传递给函数,因此它将获得一个本地副本,该副本的有效期仅与函数的作用域相同

using namespace std;

class test{
public:
    int a;
};

void runer(test testXX){
    testXX.a=10;
}

int main()
{
    test test1;
    test1.a=5;
    runer(test1);
    cout<<test1.a;
    return 0;
}

如果您希望函数能够修改传入的原始对象,然后通过非常量引用传递它
void runer(test&testXX)

您正在通过值将参数传递给函数,因此它将获得一个本地副本,该副本的有效期仅与函数的作用域相同

using namespace std;

class test{
public:
    int a;
};

void runer(test testXX){
    testXX.a=10;
}

int main()
{
    test test1;
    test1.a=5;
    runer(test1);
    cout<<test1.a;
    return 0;
}

如果希望函数能够修改传入的原始对象,则通过非常量引用传递它
void runer(test&testXX)

您的代码通过值进行调用。因此,更改不会出现在实际对象中。要更改对象属性的值,需要通过引用进行调用

void runer(test & testXX){
    testXX.a=10;
}
void runer(test &t){
    t.a = 10;
}

代码通过值进行调用。因此,更改不会出现在实际对象中。要更改对象属性的值,需要通过引用进行调用

void runer(test & testXX){
    testXX.a=10;
}
void runer(test &t){
    t.a = 10;
}

您可能是指
void runer(test&testXX)
您可能是指
void runer(test&testXX)
感谢您的帮助,现在一切都有意义了!感谢您的帮助,现在一切都有意义了!