问题描述:

#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);

}

I've been practicing classes, and pointers in C++. What i'm trying to do is have the function thingy modify the stuff2 data member in the thing class by passing a pointer to the value of stuff1. How do I go about doing this?

网友答案:

You are creating a variable of type pointer-to-int: if you want a pointer to t.stuff1, take its address:

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

Then, pass that pointer to your thing::thingy method:

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

Try this:

int *ptr;
*ptr = t.stuff1;

t.thingy( t.stuff, ptr);
网友答案:

Im probably really late to the party but i wanted to get some good comments and test

    //#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;

you cannot convert int to int* t.stuff1 is an int value, not a pointer of int try this:

    int *ptr=&t.stuff1;

and you should add ";" at the end of the define of class, like this:

    class Thing {
        ...
    };

and when you call t.thingy, the second param is int* But *ptr is an int value, not a pointer. ptr is a pointer, not *ptr. try this:

    t.thingy(t.stuff, ptr);

you should know:

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

in this case: the type of i_value j_value *p_i is int the type of p_i is int*

网友答案:

You should pass the address:

*ptr = &(t.stuff1);
相关阅读:
Top