【问题标题】:C++ Cannot pass public const string member as argument to member function of same classC ++无法将公共常量字符串成员作为参数传递给同一类的成员函数
【发布时间】:2013-11-21 09:31:36
【问题描述】:

我有一个这样定义的类(在 wxWidgets 框架中):

class SomePanel : public wxPanel{
public:
   ...
   void SomeMethod(const std::string& id){
      pointer->UseId(id);
   } 

   const std::string id = "Text"; // still in public area
   ...
}

在 pogram 的其他地方,我创建了对该对象实例的引用...

mSomePanel = new SomePanel();

...那我想做这个

mSomePanel->SomeMethod(mSomePanel->id); // Compiler gives an error saying that
                                         // there is no element named id.

在(的)类中,我可以使用这个成员变量调用相同的方法。问题出在哪里?

【问题讨论】:

  • id 是 SomePanel 的成员,传递给 self 有什么意义?
  • 粘贴的代码不完整。 (请只编译粘贴)

标签: c++ methods reference arguments argument-passing


【解决方案1】:

忽略我之前的胡言乱语。 Classname::id 应该为您提供 id。

mSomePanel->SomeMethod(SomePanel::id);  // this should work.

编辑添加更完整的代码:

这在您的 .h 中:

class SomePanel {
 public:
  static const std::string id;  // no need to have an id for each SomePanel object...
};

这在您的实现文件中(例如,SomePanel.cpp):

const std::string SomePanel::id = "Text";

现在引用 id:

SomePanel::id

另外,另一个问题可能是方法具有与成员变量同名的参数这一事实。当您调用 UseId(id) 时,编译器如何知道您指的是您的成员变量而不是函数的参数。尝试在 SomeMethod() 中更改参数的名称。

【讨论】:

  • id 既不是静态的也不是私有的。
  • 我试过了,现在我在同一个地方发现编译器错误:mSomePanel 不是类或命名空间。 – fotinsky 刚刚编辑
  • 再看一遍,不是 mSomePanel::id,而是 SomePanel::id。您给出找到它的类的名称。
  • 也试过了。现在是:尚未声明 SomePanel。
  • 尝试将其设为静态,无需为每个对象设置每个 const,并且上述语法应该可以工作。否则,我认为您刚刚发布的语法是正确的。
猜你喜欢
  • 2016-09-11
  • 2013-11-06
  • 2019-09-27
  • 2019-03-14
  • 2017-12-01
  • 1970-01-01
  • 2018-09-18
  • 2015-06-29
  • 1970-01-01
相关资源
最近更新 更多