C++ 在C+中向类传递指针+;
我试图将指针传递到我的类函数中,使其递增,并使变量使用指针保留其值。这是我的代码,它不会递增C++ 在C+中向类传递指针+;,c++,pointers,C++,Pointers,我试图将指针传递到我的类函数中,使其递增,并使变量使用指针保留其值。这是我的代码,它不会递增 #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) {
#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;
}
}
#包括“stdafx.h”
#包括
使用名称空间std;
课堂测试
{
公众:
int addTo();
测试(int*电流);
私人:
int-y;
};
测试::测试(int*currentY):
y(*当前y)
{
}
int测试::addTo()
{
y++;
返回0;
}
int main()
{
对于(;;)
{
int pointedAt=1;
int*number=&pointedAt;
试验t(编号);
t、 addTo();
cout 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;
}
}
#包括“stdafx.h”
#包括
使用名称空间std;
课堂测试
{
公众:
int addTo();
测试(int*电流);
私人:
int*y;
};
测试::测试(int*currentY):
y(当前y)
{}
int测试::addTo()
{
++*y;
返回0;
}
int main()
{
对于(;;)
{
int pointedAt=1;
测试t(&pointedAt);
t、 addTo();
couty
是一个副本。您需要某种间接寻址。您当然可以将其减少为三行或四行代码。您可以将y
作为参考。int&y;
。