在 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/