2012-04-18 155 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 *