c++ - 在 C++ 中将指针传递给类

标签 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)
{
}

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/

相关文章:

c++ - 在两个四元数之间插值很长

c++ - 如何绑定(bind)两个元组?

c# - C# ref 的技术含义

c - 在 C 中将一个数组分配给另一个数组时出错

c - 简单地通过 char 指针访问函数中的 char 数组

c++ - 如何在 C++17 中制作模板包装器/装饰器

c++ - 如何防止在非常量对象上意外调用变异函数?

c++ - 使用 boost spirit qi 解析器迭代填充 BGL 图

c++ - 什么是 'extern inline' 函数以及何时使用?

c - 我有段错误,并且不确定我的代码出了什么问题