首页 > 解决方案 > 如何在 C++ 11 中传递智能指针而不是“this”?

问题描述

我正在使用编译器。

我有两个班——班Test和班TestHelper。班级Test是班级朋友TestHelper。该类Test是我们只能从外部访问的。

现在,我们要调用TestAPI 即setVal()。这setVal()应该调用 Test2API 即 setX 并期待这个指针。我不想使用这个指针,而是想使用智能指针。我该怎么做?

这种合意的概念是因为事实上,我的班级Test很大。所以,我正在尝试为Testie创建一个助手类

class TestHelper;

class Test
{
    friend class TestHelper;
    int x;
public:
    void display() {
        std::cout << x;
     }
    void setVal(int val) {
        TestHelper testH;
        testH.setX(this, 324);
    }
};

class TestHelper
{
public:
    void setX(Test *test, int val) {
        /** some algorithm here and then  change val to something else */
        test->x = val*100;
    }
};

int main()
{
    std::cout << "Hello World!\n";
    Test x;
    x.setVal(130);
}

我尝试将原型从更改为void setX(Test *test, int val)void setX(std::shared_ptr<Test> test, int val) 但不知道如何像std::shared_ptr<Test> test这里一样传递这个指针。

标签: c++c++11

解决方案


所以这是使用共享指针的工作解决方案。由于缺少定义,该示例甚至无法编译,因此您必须将代码重组为头文件和 cpp 文件。

测试.h:

#ifndef TEST_H
#define TEST_H

#include <memory>
#include "TestHelper.h"

class Test : public std::enable_shared_from_this<Test>
{
    private:
        friend class TestHelper;
        int x;
    public:
        void display();
        void setVal(int val);
};

#endif

测试.cpp:

#include <iostream>
#include "Test.h"

void Test::display() {
    std::cout << x;
}

void Test::setVal(int val) {
    TestHelper testH;
    testH.setX(shared_from_this(), 324);
}

测试助手.h:

#ifndef TESTHELPER_H
#define TESTHELPER_H

class Test;

class TestHelper
{
    public:
        void setX(std::shared_ptr<Test> test, int val);
};

#endif

测试助手.cpp:

#include <memory>

#include "TestHelper.h"
#include "Test.h"

void TestHelper::setX(std::shared_ptr<Test> test, int val) {
    /** some algorithm here and then  change val to something else */
    test->x = val*100;
}

主.cpp:

#include <iostream>
#include <memory>

#include "Test.h"

int main(void){
    std::cout << "Hello World!\n";
    auto x = std::make_shared<Test>();
    x->setVal(130);
    x->display();
}

你可以在这里运行它:https ://paiza.io/projects/e/79dehCx0RRAG4so-sVZcQw


推荐阅读