我试图将一个指针传递到我的类函数中,让它递增,并使用指针让变量保留它的值。这是我的代码,它不会递增。
#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;
}
}
您必须存储一个指向整数的指针,因此它指向与原始变量相同的地址。
关于c++ - 在 C++ 中将指针传递给类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21504883/