C++: pure virtual assignment operator

江枫思渺然 提交于 2019-11-30 20:28:48

From section 12.8 of the standard:

13 The implicitly-defined copy assignment operator for class X performs memberwise assignment of its subobjects. The direct base classes of X are assigned first, in the order of their declaration in the base-specifier-list, and then the immediate non-static data members of X are assigned, in the order in which they were declared in the class definition. Each subobject is assigned in the manner appropriate to its type:

— if the subobject is of class type, the copy assignment operator for the class is used (as if by explicit qualification; that is, ignoring any possible virtual overriding functions in more derived classes);

The subclass is using the implicitly-defined copy assignment operator, and there is no definition of the base class's copy assignment operator, but it is declared, so you get a link error instead of a compilation error.

operator= is not inherited. Your code is meaningless in C++, so compilers are free to issue any error they want for it.

From the KB article you pointed to: http://support.microsoft.com/kb/130486

Since operator= is not inherited, any declaration of operator= in the base class is unused and unnecessary. Do not declare the operator= in the base class.

It's probably just a side-effect of how they compile, and they are just letting you know that they don't consider it a bug, so there is no need to fix it. "By design" doesn't necessarily mean that they specifically decided that this linker error is the right error message to give for this situation -- the code is wrong, you get an error, so from their point of view -- they're done.

In the example code:

class A
{
public :
   // To workaround LNK2001, comment the following line.
   virtual const A& operator=( const A& f ) = 0;
};

class B : public A
{
public :
   const A& operator=( const A& g ) {return g;}
};

B aB1, aB2;

int /*void*/ main( void )
{
   aB2 = aB1;
}

the line aB2 = aB1 does not call const A& B::operator=(const A&), but instead calls the automatically supplied B& operator=(const B&); which in turn uses the assignment operator for assigning the base portion of the class. But when it comes to linking, it turns out that that was never implemented.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!