【问题标题】:Pointer to Data Members with functions C++指向具有函数 C++ 的数据成员的指针
【发布时间】:2012-04-29 11:25:29
【问题描述】:
#include "stdafx.h"
#include <iostream>
using namespace std;

class thing{
public:
    int stuff, stuff1, stuff2;

    void thingy(int stuff, int *stuff1){
        stuff2=stuff-*stuff1;
    }
}

int main(){
    thing t;
    int *ptr=t.stuff1;
    t.thingy(t.stuff, *ptr);
}

我一直在练习 C++ 中的类和指针。我想要做的是通过传递一个指向 stuff1 值的指针来让函数 thingy 修改 thing 类中的 stuff2 数据成员。我该怎么做?

【问题讨论】:

    标签: c++ function object pointers member


    【解决方案1】:

    你正在创建一个指向 int 类型的变量:如果你想要一个指向 t.stuff1 的指针,取它的地址:

    int* ptr = &t.stuff1;
            ___^ here you are taking a reference (address)
    

    然后,将该指针传递给您的 thing::thingy 方法:

    t.thingy(t.stuff, ptr);
                    __^ don't dereference the pointer, your function takes a pointer
    

    【讨论】:

      【解决方案2】:

      试试这个:

      int *ptr;
      *ptr = t.stuff1;
      
      t.thingy( t.stuff, ptr);
      

      【讨论】:

      • 谢谢各位。那个 rly 有帮助。我环顾四周,还发现了类似这样的东西 int Thing::*ptr = thing::t.stuff1;无论如何。它到底是什么?
      【解决方案3】:

      我可能真的迟到了,但我想得到一些好的 cmets 和测试

          //#include "stdafx.h"
          #include <iostream>
           using namespace std;
      
           //class declaration
           class thing{
              public:
                  int stuff, stuff1, stuff2;
             thing(){//constructor to set default values
          stuff = stuff1 = stuff2 = 10;
              }
      
      
               void thingy(int param1, int *param2){
                  stuff2=param1-*param2;
                }
              };
      
             //driver function
             int main(){
                thing t;//initialize class
            cout << t.stuff << ' ' << t.stuff1 << ' ' << t.stuff2 << endl;//confirm default values
                int *ptr= &t.stuff1;//set the ADDRESS (&) of stuff1 to an int pointer
            cout << *ptr << endl;
                 t.thingy(t.stuff, ptr); //call function with pointer as variable
             cout << t.stuff1;
                }
      

      【讨论】:

        【解决方案4】:
            int *ptr=t.stuff1;
        

        您不能将 int 转换为 int* t.stuff1 是一个 int 值,而不是 int 的指针 试试这个:

            int *ptr=&t.stuff1;
        

        你应该添加“;”在类定义的最后,像这样:

            class Thing {
                ...
            };
        

        当你调用 t.thingy 时,第二个参数是 int* 但是 *ptr 是一个 int 值,而不是指针。 ptr 是一个指针,而不是 *ptr。试试这个:

            t.thingy(t.stuff, ptr);
        

        你应该知道:

            int i_value = 1;
            int* p_i = &i_value;
            int j_value = *p_i;
        

        在这种情况下: i_value j_value *p_i 的类型是 int p_i 的类型是 int*

        【讨论】:

          【解决方案5】:

          你应该传递地址:

          *ptr = &(t.stuff1);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2023-03-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多