错误 C2248:“CObject::CObject” : 无法访问类“CObject”中声明的私有成员

发布于 2024-11-10 18:10:55 字数 266 浏览 2 评论 0原文

我将具体说明我的错误原因。 请纠正我的错误:

代码

   private:
   CStringArray m_strMnemonicArray;

   public:
   CStringArray getMnemonicSet();
   CStringArray CParserDlg::getMnemonicSet()
   {
      return m_strMnemonicArray;
   }

I will specify the reason for my error.
Please rectify my error:

CODE

   private:
   CStringArray m_strMnemonicArray;

   public:
   CStringArray getMnemonicSet();
   CStringArray CParserDlg::getMnemonicSet()
   {
      return m_strMnemonicArray;
   }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

长发绾君心 2024-11-17 18:10:55

我已将多个任务自动化到如下所示的函数中:

    CStringArray CParserDlg::getMnemonicSet();

通过引用返回 CStringArray,而不是值。

   CStringArray& CParserDlg::getMnemonicSet();

这不仅可以消除编译器错误,而且通过(常量)引用传递对象(例如 CStringArray)也是 C++ 中的一条经验法则,如果不是,则通过指针传递对象。

原因是按值传递会产生对象的临时副本。如果没有意识到这一点,按值传递对象将在执行时间和错误结果方面产生不良结果(即期望传入的对象在函数内发生更改)。

该错误的根本原因是 CObject 不可复制,但您正在按值传递 CStringArray(派生自 CObject)。按值传递意味着编译器将尝试创建对象的临时副本。由于 CObject 没有可用的复制构造函数,因此编译器会给出错误。

但要补充的是,我比 CStringArray 更喜欢这个:

  #include <vector>
  std::vector<CString> CStringVector;

那么你就不会得到编译器错误,因为向量是可复制的(但你会得到执行时间的问题和我之前提到的可能的错误结果)。

I have automated several tasks into a function shown below:

    CStringArray CParserDlg::getMnemonicSet();

return the CStringArray by reference, not value.

   CStringArray& CParserDlg::getMnemonicSet();

Not only would this get rid of the compiler error, it is also a rule of thumb in C++ to pass objects such as CStringArray by either (const) reference, or if not, by pointer.

The reason is that passing by value incurs a temporary copy of the object. If not aware of it, passing objects by value will yield undesirable results, both in execution time and in wrong results (i.e. expecting the passed in object to have changed within the function).

The underlying reason for the error is that CObject is not copyable, but you are passing a CStringArray (which is derived from CObject) by value. Passing by value means that the compiler will attempt to make a temporary copy of the object. Since CObject has no available copy constructor, the compiler gives you the error.

But to add, I would much prefer this than CStringArray:

  #include <vector>
  std::vector<CString> CStringVector;

Then you wouldn't have gotten the compiler error, since vector is copyable (but you would get the problem of the execution time and possible erroneous results I mentioned earlier).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文