【问题标题】:Passing class pointer to a function将类指针传递给函数
【发布时间】:2018-02-06 13:30:50
【问题描述】:

我想在另一个函数中使用不同的 WText 实例,但由于我只想拥有一个控制函数,我想将它们传递到那里。

当前设置的代码可以编译,但由于一些我不理解的内存错误而失败。

class mode : public WApplication
{
//..
private:
//..
void someFunc();
void control(WText* texty);
WText* text;
WText* text2;
WText* text3;
//...etc
};

void mode::someFunc(){
     control(text); //how to pass it?
     //might pass  text2 or text3 as well
}

void mode::control(WText* texty){
     texty->setText("blabla");
     //..
}

【问题讨论】:

  • 此代码不会因内存错误而失败!请提供minimal reproducible example
  • Whenwhere 程序会失败吗?它是如何失败的(崩溃或意外结果)?您是否使用过调试器来帮助您找到问题?像Valgrind 这样的内存调试器怎么样?
  • 为什么是text 和其他指针?只是永远不要使用原始拥有指针作为成员

标签: c++ class pointers arguments wt


【解决方案1】:

text 成员是指向对象 WText 的指针, 您需要做的第一件事是创建一个新的 WText 对象:

void mode::someFunc() {
    text = new WText();
    control(text);
}

请记住使用后销毁文本对象。

【讨论】:

  • 谢谢,实际上我调用了 text = new WText();在控制(文本)之后没有注意到它。 :(
  • 或者在构造函数中设置你需要的东西?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多