c++ - C++ 中的委托(delegate)(或类似的东西)

标签 c++ delegates

在 C++ 中,我有:

//Base1.h
#ifndef BASE1_H
#define BASE1_H
#include <iostream>
#include <string>
#include "Base2.h"

using namespace std;

class Base1{
    private:
        string name;
    public:
        Base1(string _name);
        void printSomething();
        string getName();
};
#endif

Base1.cpp我实现构造函数Base1(string _name)string getName()正常情况下,printSomething() :

void Base1::printSomething(){
    Base2 b2;
    // how to pass a parameter in the following code?
    b2.printBase1();
}

// This is Base2.h
#ifndef BASE2_H
#define BASE2_H

#include <iostream>
#include <string>
#include "Base1.h"

using namespace std;

class Base2{
    public:
      Base2();
      void printBase1(Base1 b);
};
#endif

Base2()我照常实现的构造函数,这是我的 printBase1(Base1 b) :

void Base2::printBase1(Base1 b){
    cout << b.getName();
}

所以,最后我想用printSomething()Base1类,但我不知道如何将参数传递给 b2.printBase1()printSomething()如我的代码中所示。有没有像 b2.printBase1(this) 这样的东西在 C++ 中?如果没有,您能给我一个建议吗?

最佳答案

由于 this 是 C++ 中的指针,因此需要取消引用它:

b2.printBase1(*this);

请注意,您有循环包含,您应该从 Base1.h 中删除 #include "Base2.h"。还要考虑通过 (const) 引用传递参数,特别是对于非 POD 类型,否则您可能无法获得预期的行为。

例如,您的签名是

void printBase1(Base1 b);

当你调用它时,你在函数中创建了参数的拷贝,从而对拷贝进行操作。您应该将其更改为:

void printBase1(Base1& b);

void printBase1(const Base1& b); //if you don't change b

仅当您确定需要拷贝时才按值传递。

关于c++ - C++ 中的委托(delegate)(或类似的东西),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11000620/

相关文章:

ios - 委托(delegate)函数不调用

c# - 在 C# 中调用具有未知类型和参数数量的函数

ios - 在 ViewControllerB 到 ViewControllerA 之间传递数据,委托(delegate)不会被调用

ios - Sinch didReceiveIncomingCall 从未调用过

c++ - 如何在 IplImage 上使用 cv::imencode?

c++ - 用 clang 编译 c++ - 新手

c++ - 如何在 CLion 中显示 C++ 的参数名称提示?

C++ 大型二维数组访问冲突

c++ - 帮助 boost 语法

c# - 如何在 C# 中使用 Dictionary<> 的聚合方法?