Я пытаюсь передать указатель в мою функцию классов, увеличил его и сохранил значение переменной с помощью указателей. Heres мой код, он не увеличивается.
#include "stdafx.h"
#include <iostream>
using namespace std;
class test
{
public:
int addTo();
test(int * currentY);
private:
int y;
};
test::test(int * currentY):
y(*currentY)
{
}
int test::addTo()
{
y++;
return 0;
}
int main ()
{
for (;;)
{
int pointedAt = 1;
int * number = &pointedAt;
test t(number);
t.addTo();
cout <<*number;
char f;
cin >>f;
}
}
Это должно сделать это:
#include "stdafx.h"
#include <iostream>
using namespace std;
class test
{
public:
int addTo();
test(int * currentY);
private:
int *y;
};
test::test(int *currentY):
y(currentY)
{}
int test::addTo()
{
++*y;
return 0;
}
int main ()
{
for (;;)
{
int pointedAt = 1;
test t(&pointedAt);
t.addTo();
cout << pointedAt;
}
}
Вы должны сохранить указатель на целое число, поэтому он ссылается на тот же адрес, что и исходная переменная.
y
это копия. Вам понадобится какое-то косвенное обращение.