在我刚刚进行的测试之前,我相信只有构造函数不会在C++中继承.但显然,任务operator=不是......
operator+=,operator-=...?事实上,我在做一些CRTP时遇到了这个问题:
template<class Crtp> class Base
{
inline Crtp& operator=(const Base<Crtp>& rhs) {/*SOMETHING*/; return static_cast<Crtp&>(*this);}
};
class Derived1 : public Base<Derived1>
{
};
class Derived2 : public Base<Derived2>
{
};
Run Code Online (Sandbox Code Playgroud)
是否有任何解决方案可以使其工作?
编辑:好的,我已经解决了这个问题.为什么以下不起作用?如何解决问题?
#include <iostream>
#include <type_traits>
// Base class
template<template<typename, unsigned int> class CRTP, typename T, unsigned int N> class Base
{
// Cast to base
public:
inline Base<CRTP, T, N>& operator()()
{
return *this;
}
// Operator =
public: …Run Code Online (Sandbox Code Playgroud) 我遇到了operator =的继承问题.为什么这段代码不起作用,解决它的最佳方法是什么?
#include <iostream>
class A
{
public:
A & operator=(const A & a)
{
x = a.x;
return *this;
}
bool operator==(const A & a)
{
return x == a.x;
}
virtual int get() = 0; // Abstract
protected:
int x;
};
class B : public A
{
public:
B(int x)
{
this->x = x;
}
int get()
{
return x;
}
};
class C : public A
{
public:
C(int x)
{
this->x = x;
}
int get() …Run Code Online (Sandbox Code Playgroud)