我有以下问题:
//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);
}
cpp:
//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是框架中的内置类。我无法将受保护的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
(来自A
的)指针初始化非指针new A
可能是一个错误。我将
->
更改为.
,因为a
不是指针。