c++ - 如何在 C++ 11 中传递智能指针而不是“this”?
问题描述
我正在使用c++11编译器。
我有两个班——班Test
和班TestHelper
。班级Test
是班级朋友TestHelper
。该类Test
是我们只能从外部访问的。
现在,我们要调用Test
API 即setVal()
。这setVal()
应该调用
Test2
API 即 setX 并期待这个指针。我不想使用这个指针,而是想使用智能指针。我该怎么做?
这种合意的概念是因为事实上,我的班级Test
很大。所以,我正在尝试为Test
ie创建一个助手类
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
这里一样传递这个指针。
解决方案
所以这是使用共享指针的工作解决方案。由于缺少定义,该示例甚至无法编译,因此您必须将代码重组为头文件和 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
推荐阅读
- ruby - Ruby 控制台 - 带出口的多行命令
- python-3.x - 对 pandas 列中的所有元素求和
- reactjs - 将链接输入与另一个输入反应(链接多选)
- sql - BoM 和子装配 CTE 查询
- powershell - PowerShell - 从 Invoke-Command 内部调用时,ShouldProcess 不起作用
- javascript - 当且仅当它在 React Native 中返回 null 时,如何使函数再次运行?
- javascript - 如何循环一些代码,以便每次确认()返回 true 时重复?
- coinbase-api - 有没有办法通过他们的 API 查看子投资组合的 Coinbase Pro 交易?
- .net - 使用 ODP.NET 非托管驱动程序 C#.NET 进行 kerberos 身份验证
- elasticsearch - 根据另一个索引中的值更新索引中字段的值