【问题标题】:Random letters in C++ structC++结构中的随机字母
【发布时间】:2014-11-22 14:13:24
【问题描述】:

所以我有一个我正在制作的结构,我也可以制作一个类,但是当我尝试获取它们的属性时......它给了我随机的字母。就像完全随机一样。我看到类似“(▌ ¶∞♥!¶↑♥!¶≤    ≈ ¶⌠  ☻!¶≈   Ç┌ ¶√   Φ`◄¶ ◄▬¶Ç┌ ¶√   Ç☻V♫√   ╨┘ ¶⌠ ╨┘ ¶⌠   0│"。

我已经将它精简为一些完全基本的东西,但我仍然不知道它为什么这样做。

struct Example
{
    const char* Whatever = "Hello";
};

当我这样做时

Example* exampleObj;
print(exampleObj->Whatever);

它会显示随机字母。随机字母因程序的执行而异。

【问题讨论】:

  • exampleObj 只是一个不指向任何东西的指针。因此,您正在访问内存的随机部分。试试看:Example* exampleObj = new Example;
  • 我认为它们是同一件事,但有两种不同的方法。我刚刚试过了,但还是不行,很遗憾。
  • 你也没有终止字符串。
  • 使用常规对象。忘记不必要的指针。
  • @GREnvoy:字符串已终止。

标签: c++ class random struct letters


【解决方案1】:

指针是一个变量,用于保存对象所在内存中的地址。所以声明一个指针是不够的,你还需要创建一些东西让它指向。这意味着您需要留出一些内存来放置您的对象。

Example* exampleObj; // at the moment exampleObj contains spurious data

这只是一个指针。但是你还没有创造任何东西让它指向。如果您尝试访问它,您将访问虚假垃圾!

所以要分配一块包含有效对象的内存,您需要像这样使用new

Example* exampleObj = new Example; // new returns a chunk of valid memory

现在为指针分配了一个有效的内存地址,其中包含您刚刚使用new 创建的对象。

注意:

通常不需要使用new 手动分配对象。相反,您可以使用 automatic 变量而不是指针:

Example exampleObj; // note no * means its not a pointer but a whole object

解决方案:

所以我们有两种方法可以解决您的问题。创建一个new 对象并将其地址分配给您的指针或创建一个automatic 对象:

// Solution 1:
Example* exampleObj = new Example; // Must remember to delete (smart pointer?)
print(exampleObj->Whatever);

// Solution 2 (usually MUCH better)
Example exampleObj;
print(exampleObj.Whatever); // note: uses . rather than ->

【讨论】:

  • 谢谢。这解释了它,我把它记下来了。
  • 确保在示例 1 中删除了 exampleObj。
猜你喜欢
  • 1970-01-01
  • 2017-04-11
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 2013-12-06
  • 1970-01-01
  • 2017-12-14
  • 2019-09-08
相关资源
最近更新 更多