且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

函数返回复杂类

更新时间:2022-05-06 18:28:03

如有疑问,请搜索Google:编译器错误C2248 [
If in doubt, search Google: Compiler Error C2248[^]

''member'' : cannot access ''access'' member declared in class ''class''
Members of a derived class cannot access private members of a base class. You cannot access private or protected members of class instances.


"当然是错字,是一个".-我们怎么知道?我们不能假设.对吧?

现在,当您解决它时,这是我的答案:

CObject(从其派生CArray)声明了一个私有副本构造函数,因此,除非在派生类中实现该构造函数,否则默认情况下不能使用该构造函数.

现在,当您按值返回CArray时,它是复制构造函数,因此它的基本CObject复制const被调用(这会产生错误).而是尝试返回作为引用或指针(不会导致调用副本const)



如OP所述,这不是一个愚蠢的问题.
实际上,很多人都犯了一个错误.
一个人不能按值返回从CObject派生的任何类对象,因为它将导致调用CObject的副本构造函数,这是不允许的.
"is of course a typo, it is "one" " - How do we know ?? We can''t assume. Right ?

Now as you resolved it, here is my anwser :

CObject (from where CArray is derived from) declares a private copy constructor, so that constructor can''t be used by default unless it''s implemented in a derived class.

Now when you return CArray by value, then it''s copy constructor and hence it''s base CObject copy const is called (and this gives an error). Instead try to return as reference or pointer (which wont lead to calling of copy const)



This is not a stupid question as mentioned by OP.
In fact an error made by many.
One cannot return any class object derived from CObject by value as it will lead to calling of copy constructor of CObject, which is not allowed


在函数中按值返回似乎很好,因为创建的对象将被发送给调用者,没有任何问题.尽管如果对象的大小很大,则可能会降低性能开销.

第二个函数声明接受一个引用,您可以在函数内部分配该引用或更改该引用值,这可以正常工作,但这将使调用者可用于创建对象并通过引用传递该对象.

约定更像:如果您不希望更改它们,则通过const引用传递所有对象.如果希望在函数内对其进行更改,则可以通过指针传递它们.

所以我会说要么保留原始方法(在复制构造函数调用时降低性能开销),要么使用指针执行相同的操作.

功能:
Return by value in you function seems fine as the copy of the created object will be sent to the caller and nothing is problamatic. although if the size of the object is big then it might be a little performance overhead.

The second function declaration accepts a reference and you will assign that reference or change that reference values inside the function, which could work fine but this will make the caller resposible for creating the object and passing it by reference.

The convention is more like: pass all objects by const reference if you dont want them to get changed. pass them by pointer if you want them to get changed inside the function.

so I will say either you keep the original methid as is (little performance overhead on copy constructor call) or use pointer to do same thing.

function:
void GetClass(CString C, one * class_one)
{
 class_one = new one();
  if(C == "GO")
   {
     class_one->Add(5.4);
   }
   else
   {
    class_one->Add(3.5);
   }
}



并致电为:



and call as:

One *one;
GetClass(C, one);



我可能错了,也许有人可以纠正我的意见.



I might be wrong, someone can perhaps correct me of ratify this.