相关疑难解决方法(0)

operator =和在C++中没有继承的函数?

在我刚刚进行的测试之前,我相信只有构造函数不会在C++中继承.但显然,任务operator=不是......

  1. 这是什么原因?
  2. 是否有任何解决方法来继承赋值运算符?
  3. 是不是也为的情况下operator+=,operator-=...?
  4. 是否继承了所有其他函数(除了构造函数/运算符=)?

事实上,我在做一些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)

c++ inheritance operator-overloading crtp

36
推荐指数
3
解决办法
2万
查看次数

在C++中继承operator =的麻烦

我遇到了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)

c++ inheritance abstract-class operator-keyword

17
推荐指数
1
解决办法
6012
查看次数