#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Bird{
public:
int A;
Bird(int Y){A = Y;}
int retrieve(){return A;}
} ;
int main(){
Bird * C =new Bird(6);
cout<< C.retrieve()<<endl;
return 0;
}
我无法访问由C指针指向的对象的retrieve()方法(该对象由C指向)。有没有办法做到这一点。请让我知道。我使用vscode V1.29.1
您正在堆上实例化Bird
实例,并在名为C
的变量中存储指向该对象的指针。在访问数据成员或成员函数之前必须取消引用指针,即
std::cout << C->retrieve() << "\n";
// or, as @PeteBecker has pointed out in the comments
std::cout << (*C).retrieve() << "\n";
另外,别忘了
delete C;
甚至更好:使用<memory>
标头和std::make_unique
,这使您无需手动清理指针。
#include <memory>
auto C = std::make_unique<Bird>(6);
std::cout<< C->retrieve() << "\n";