2012-04-18 148 views
1
#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的值的指针来修改thing类中的stuff2数据成员。我如何去做这件事?指针数据成员函数C++

回答

2

您正在创建类型的变量指针到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 
0

试试这个:

int *ptr; 
*ptr = t.stuff1; 

t.thingy(t.stuff, ptr); 
+0

THX的家伙。那帮忙。我环顾四周,也发现了这样的事情 int Thing :: * ptr = thing :: t.stuff1; 无论如何都沿着这些线。究竟是什么? – Painguy 2012-04-18 20:30:25

0

您应该通过地址:

*ptr = &(t.stuff1); 
0

林大概真的迟到了,但我希望得到一些很好的意见和测试

//#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; 
      } 
0
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 *