【问题标题】:cpp: can't get the value of member via pointer by using ->cpp:无法使用->通过指针获取成员的值
【发布时间】: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


【解决方案1】:

正如评论者所说 - A 中的 codeB 中的 code 无关。此外,当您通过指向A 的指针访问code 时,您访问的是A::code。由于我们真的不知道您想要实现什么,您可以例如从 B 中删除 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;
};

【讨论】:

  • 谢谢!更改我的代码后立即查看您的答案〜你是对的!所以@immibis,非常感谢!
猜你喜欢
  • 2013-01-03
  • 2021-11-17
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多