C++ cpp:can';t使用->;通过指针获取成员的值;
我有一个关于如何在cpp中使用->的问题。我需要做的是使用在类C中创建的指针a获取类B的私有成员值code,我的代码的结构如下: 我将原始代码粘贴到此处:C++ cpp:can';t使用->;通过指针获取成员的值;,c++,class,shared-ptr,member,C++,Class,Shared Ptr,Member,我有一个关于如何在cpp中使用->的问题。我需要做的是使用在类C中创建的指针a获取类B的私有成员值code,我的代码的结构如下: 我将原始代码粘贴到此处: //detector.hpp class Detector{ public: std::string name; int code; } //detectorH.hpp class detectorH : public Detector { private: std::string name; int code; publi
//detector.hpp
class Detector{
public:
std::string name;
int code;
}
//detectorH.hpp
class detectorH : public Detector {
private:
std::string name;
int code;
public:
detectorH();
std::shared_ptr<Detector> h_detector();
}
//detectorH.cpp
detectorH::detectorH(){
name = "h";
code = 1111;
}
std::shared_ptr<Detector> h_detector(){
return std::make_shared<detectorH>();
}
//findCode.cpp
class findCode{
private:
std::vector<std::shared_ptr<Detector>> detectors;
public:
findCode(){
detectors.push_back(h_detector());
void find(){
for(auto& d:detectors){
std::cout << d->code << std::endl;
}
}
}
};
//detector.hpp
类检测器{
公众:
std::字符串名;
int代码;
}
//检测器
类别检测器:公共检测器{
私人:
std::字符串名;
int代码;
公众:
检测器();
std::共享_ptr h_检测器();
}
//检测器
detectorH::detectorH(){
name=“h”;
代码=1111;
}
std::共享_ptr h_检测器(){
返回std::make_shared();
}
//findCode.cpp
类findCode{
私人:
向量检测器;
公众:
findCode(){
探测器。推回(h_探测器());
void find(){
用于(自动和d:探测器){
std::cout code正如评论员所说,A
中的code
与B
中的code
无关。此外,当您通过指向A
的指针访问A::code
时,您可以访问A::code>中的代码>:
class A {
public:
int code;
};
class B : public A {
public:
B() { code = 1111 };
};
或者将其初始化为某个值:
class A {
public:
A() : code{ 2222 } { }
int code;
};
class B : public A {
public:
B() : code{ 1111 } { }
private:
int code;
};
您也可以在B
的构造函数中执行此操作:
class B : public A {
public:
B() : code{ 1111 } { A::code = 2222; }
private:
int code;
};
As.push_-back(B());
是错误的。B()
不返回指针,它返回一个对象。@Barmar谢谢你的回答!是的B()返回一个对象,我认为push_-back(B())是将对象作为?添加到向量中。@Barmar每个对象都有一个成员代码,它可以被向量的指针a访问,如??B:B(){
是一个语法错误。请复制并粘贴您的真实代码。只有B中的代码才能访问B的私有成员。这就是私有的意思。此外,a的代码与B的代码完全不同,即使您使用了相同的名称。变量不能被覆盖。谢谢!更改我的代码后立即查看您的答案~您是对的!因此@immibis,非常感谢!