C++ 无法将 public const string 成员作为参数传递给同一类的成员函数

标签 c++ methods reference arguments argument-passing

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

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

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

我在程序中的其他地方创建了对此对象实例的引用...

mSomePanel = new SomePanel();

...那么我想做这个

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

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

最佳答案

请忽略我之前的废话。 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() 中更改参数的名称。

关于C++ 无法将 public const string 成员作为参数传递给同一类的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19874880/

相关文章:

php - 在 PHP 函数/方法中返回的最佳实践

c++ - 递归模板 - 常量 n 大小数组 -> n-1 大小就地?

c++ - glibc 应用程序保留未使用的内存直到退出

python - 是否可以为python中的类设置默认方法?

java - ButtonGrid 的邻近检查器(如雷区游戏)

c++ - 引用文献 : am I going to go out of scope?

Python deepcopy,对象变化中的字典值

c# - 缺少引用

c++ - C++中的 "type of expression"是什么?

c++ - 为什么 CPP 中 WaitForSingleObject 函数的这两种不同行为