【发布时间】:2017-03-06 00:30:11
【问题描述】:
我有一个关于如何在 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;
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;
}
}
}
};
但问题是 cout 始终为 0,这意味着我未能获得正确的值。我不知道为什么......并且没有错误消息,所以我不知道如何修复它......任何人都可以给我一个提示?非常感谢!
【问题讨论】:
-
As.push_back(B());是错误的。B()不返回指针,而是返回一个对象。 -
@Barmar 感谢您的回复!是的 B() 返回一个对象,我认为 push_back(B()) 是用于将对象添加到向量 As 中?
-
@Barmar 每个对象都有一个成员code,可以通过向量As的指针a来访问??
-
B:B(){是语法错误。请复制并粘贴您的真实代码。 -
只有B中的代码才能访问B的私有成员。这就是私人的意思。此外,即使您给出了相同的名称,A 的代码也与 B 的代码完全分开。变量不能被覆盖。
标签: c++ class shared-ptr member