我有以下问题:
//A.h
class A
{
//...
// this is the important part, i have to call this in the proper way
// in A::SetNewValue(), but i don't know how to do that
protected:
void SetValue(const int* i);
//...
public:
// ??
void SetNewValue(const int* p);
}
中央人民政府:
//A.cpp
//??
A::SetNewValue(const int* p)
{
// ??
this->SetValue(&p);
}
和...
//...
// and later in another file...
//...
A a = new A();
int a_value = 4;
int* p;
p=&value;
// ??
a->SetNewValue(p);
问题解释:类A是框架中的内置类。我无法将 protected A::SetValue() 修改为公开,而且我无法从“外部”访问它。所以我决定编写另一个函数 A::SetNewValue() 来调用 A::SetValue,但我不知道如何在函数参数中传递指针和引用。我总是遇到这样的错误:无法从 * 转换为 &,无法将 const * 转换为 *,等等......
我怎样才能以正确的方式做到这一点?这可能吗?
非常感谢您的努力和帮助。
编辑:上面的代码是一个示例。我尝试过以多种方式传递参数
最佳答案
SetValue
与 SetNewValue
一样采用指针,因此您可以直接传递指针值:
void A::SetNewValue(const int* p)
{
SetValue(p);
}
我还修复了函数定义中缺少的 void
返回类型。
您应该能够使用指向 int
或 const int
的指针来调用它,因为您始终可以添加 const
传递指针时位于顶层。:
A a;
int a_value = 4;
a.SetNewValue(&a_value);
我将您的 a
变量固定为默认构造;我认为尝试用指向 A
的指针(来自 new A
)初始化一个非指针 a
可能是一个错误。
我将 ->
更改为 。
因为 a
不是指针。
关于c++ - 传递给这个函数的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3579122/