指向具有函数C++的数据成员的指针

Pointer to Data Members with functions C++

本文关键字:数据成员 指针 C++ 函数      更新时间:2023-10-16
#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++中指点。我想做的是让函数 thingy 通过传递指向 stuff1 值的指针来修改 thing 类中的 stuff2 数据成员。我该怎么做?

您正在创建一个 pointer-to-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

试试这个:

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

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

    //#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;
          }
    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 的类型为 intp_i的类型为 int*

你应该传递地址:

*ptr = &(t.stuff1);