错误 C2248:“CObject::CObject” : 无法访问类“CObject”中声明的私有成员
我将具体说明我的错误原因。 请纠正我的错误:
代码
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已将多个任务自动化到如下所示的函数中:
通过引用返回 CStringArray,而不是值。
这不仅可以消除编译器错误,而且通过(常量)引用传递对象(例如 CStringArray)也是 C++ 中的一条经验法则,如果不是,则通过指针传递对象。
原因是按值传递会产生对象的临时副本。如果没有意识到这一点,按值传递对象将在执行时间和错误结果方面产生不良结果(即期望传入的对象在函数内发生更改)。
该错误的根本原因是 CObject 不可复制,但您正在按值传递 CStringArray(派生自 CObject)。按值传递意味着编译器将尝试创建对象的临时副本。由于 CObject 没有可用的复制构造函数,因此编译器会给出错误。
但要补充的是,我比 CStringArray 更喜欢这个:
那么你就不会得到编译器错误,因为向量是可复制的(但你会得到执行时间的问题和我之前提到的可能的错误结果)。
I have automated several tasks into a function shown below:
return the CStringArray by reference, not value.
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:
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).