class Cat
{
public:
int name;
Cat();
int getName();
}
如果我有:
Cat* pointer = new Cat();
pointer->getName();
pointer->name; //this doesn't work
那么如何访问数据成员:name?
答案 0 :(得分:3)
它运作得很好:http://ideone.com/3E5Uec
#include <iostream>
using std::cout; using std::endl;
class Cat
{
public:
int name;
Cat() : name(0) { }
int getName() { return name; }
};
int main()
{
Cat* pointer = new Cat();
pointer->name = 42;
cout << "getName: " << pointer->getName() << endl;
cout << "name: " << pointer->name << endl;
delete pointer;
}
请注意,我必须对您提供的代码添加一些内容,因为它没有像您提供的那样进行编译:
;
pointer->name
的结果以验证其是否有效