class Cat
{
public:
int name;
Cat();
int getName();
}
如果我有:
Cat* pointer = new Cat();
pointer->getName();
pointer->name; //this doesn't work
那么如何访问数据成员:名称?
class Cat
{
public:
int name;
Cat();
int getName();
}
如果我有:
Cat* pointer = new Cat();
pointer->getName();
pointer->name; //this doesn't work
那么如何访问数据成员:名称?
它工作得很好: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
以验证它是否有效