我有一个这样定义的类(在 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/