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 データ メンバーを変更する関数を持たせることです。どうすればこれを行うことができますか?

4

5 に答える 5

2

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
于 2012-04-18T04:44:56.827 に答える
0

これを試して:

int *ptr;
*ptr = t.stuff1;

t.thingy( t.stuff, ptr);
于 2012-04-18T04:40:21.333 に答える
0
    int *ptr=t.stuff1;

int を int* に変換することはできません t.stuff1 は int 値であり、int のポインターではありません。これを試してください。

    int *ptr=&t.stuff1;

「;」を追加する必要があります 次のように、クラスの定義の最後に:

    class Thing {
        ...
    };

t.thingy を呼び出すと、2 番目のパラメーターは 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*

于 2012-04-18T06:06:16.837 に答える
0

アドレスを渡す必要があります。

*ptr = &(t.stuff1);
于 2012-04-18T04:45:44.753 に答える
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;
          }
于 2012-04-18T04:55:19.933 に答える