简体   繁体   English

C++ 成员变量指针

[英]C++ member variable pointers

I am sure this is a basic question, but I keep receiving memory access errors when I think I am doing this correctly.我确信这是一个基本问题,但是当我认为我正确执行此操作时,我不断收到 memory 访问错误。

What I want to do:我想做的事:

class A{
  string name;
  string date;
}

main{
  A *a = new A();
  a->name= someFunct();
  a->date= someFunct();

  B b;
}
class B{
  A *a;
  printf("%s", a->name); //retrieving data set in main
}

I essentially need to assign some overall settings in one class and want to be able to access those settings throughout the application in the most efficient way.我基本上需要在一个 class 中分配一些整体设置,并希望能够以最有效的方式在整个应用程序中访问这些设置。

You're passing a std::string to printf, you need to pass a c string.您将 std::string 传递给 printf,您需要传递 c 字符串。

printf("%s", a->name.c_str())

In addition to Andreas' answer, you are not initialising *a in B. Just because they are named the same does not mean that they are pointing to the same thing.除了 Andreas 的回答,您没有在 B 中初始化 *a。仅仅因为它们的名称相同并不意味着它们指向同一个东西。 You need to say something like你需要说类似

b.a = new A();

in your main.在你的主要。 Otherwise ba is an empty pointer.否则 ba 是一个空指针。

Ie. IE。 You need to create an instance of a on your b instance.您需要在 b 实例上创建 a 的实例。 Alternatively to keep a bit closer to your current code you could do:或者,为了更接近您当前的代码,您可以这样做:

int main(char* args[]){
  A *a = new A();
  a->name= someFunct();
  a->date= someFunct();

  B b;
  B.a = a;
  return 0;
}

Maybe this will be useful too:也许这也很有用:

class A
{
public: //you forgot this
        //defaut is private
   string name;
   string date;
};

int main()
{
   A *a = new A();
   a->name = someFunct();
   a->date = someFunct();

   delete a; //maybe you should do it
}

class B
{
   A *a;

   .....
   printf("%s", a->name.c_str());
   .....
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM