C++ 通过C+;中的指针将子对象值传递给被调用类+;
原来的代码看起来很混乱,所以我删除并添加了其他解释性代码。希望不会引起同样的混乱 将其视为C++ 通过C+;中的指针将子对象值传递给被调用类+;,c++,qt,pointers,C++,Qt,Pointers,原来的代码看起来很混乱,所以我删除并添加了其他解释性代码。希望不会引起同样的混乱 将其视为主计算(类似于管理类) 水电站: 其他类(执行某些工作并返回结果的类) 水电站: 非常简单: class Child { int m_Data = 0; public: Child(int Data) : m_Data(Data) {}; int doSomething() { // Do something ("Child calculation")
主计算
(类似于管理类
)
水电站:
其他类
(执行某些工作并返回结果的类)
水电站:
非常简单:
class Child
{
int m_Data = 0;
public:
Child(int Data) : m_Data(Data) {};
int doSomething()
{
// Do something ("Child calculation") , for example:
int a = 0, b = 0, c = 0, d = 0, e = 0, f = m_Data, r = 0;
r = a * b * c * d * e * f + a * b * c + f + 5;
return r;
}
};
使用:
--
如果您更喜欢使用指针:…您写道:“将一个值作为指针从父级传递给子级,并使子级计算结果存储在该父级值指针指向的位置。”
使用:
--
- 它可以是
而不是std::vector
int
您可以通过使用
共享\u ptr
来改进它。或者按照问题的其他建议返回doSomething()
中的值。即使您现在返回向量,由于返回值优化,也不会出现性能问题。您显示的初始代码与您描述的代码使用方式不匹配。Child
类中没有doSomething
。至于如何将值“传递”回“父”对象,为什么Child::doSomething
不能直接返回值呢?如果不可能的话,您的代码和描述中似乎缺少了一些内容。因此,请提供一些帮助来改进您的问题。int doSomething()
@Someprogrammerdude我的例子中的指针是指向QVector的指针,我在将子对象的计算值分配给父对象值指针时遇到了一个异常。我会发布异常。你能发布工作的、可编译的示例代码吗?因为您当前的代码很难理解。我做的第一件事是检查指针是否为null,但它不是,我在调试器中看到了它的有效地址,它只是在赋值过程中失败了。
whatever* whatever::somefunction(const String& nothing)
{
const auto newWhatever = new whatever{nothing, _cache};
return newWhatever; // not important
}
private: std::Vector<int> _cache;
class OtherClass
{
std::vector* _value;
std::vector _result;
public:
OtherClass(const string& nothing, std::vector<int>* cache) : _value{cache}
void calculateresult()
{
*_value = _result;
}
}
template <typename T>
QVector<T> &QVector<T>::operator=(const QVector<T> &v)
{
if (v.d != d) {
QVector<T> tmp(v);
tmp.swap(*this);
}
return *this;
}
class Child
{
int m_Data = 0;
public:
Child(int Data) : m_Data(Data) {};
int doSomething()
{
// Do something ("Child calculation") , for example:
int a = 0, b = 0, c = 0, d = 0, e = 0, f = m_Data, r = 0;
r = a * b * c * d * e * f + a * b * c + f + 5;
return r;
}
};
Child Chl(5);
int Result = Chl.doSomething(); // Result is 10
class Child
{
int * m_pData = nullptr;
public:
Child(int * pData) : m_pData(pData) {};
void doSomething()
{
// Do something ("Child calculation") , for example:
int a = 0, b = 0, c = 0, d = 0, e = 0, f = *m_Data, r = 0;
r = a * b * c * d * e * f + a * b * c + f + 5;
*m_pData = r; // "store in the location pointed"
}
};
int Data = 5; // "A value from Parent"
Child Chl(&Data); // "To the Child, as a pointer"
Chl.doSomething(); // Data is 10
class Child
{
public:
Child (int* value) : Localvalue{value};
int* Localvalue;
int Resultvalue;
void doSomething() {
if (Localvalue != nullptr)
*Localvalue = Resulvalue;
}
};