小编Mir*_*cir的帖子

C++ 从类方法返回 const 反向迭代器,但方法不能是 const?

我试图从类方法返回 const 反向迭代器。但是当我将方法标记为 时,我的代码无法编译const。没有const代码编译就没有问题。

知道为什么吗?

#include <iostream>
#include <vector>

template <class ValueType>
class DynamicDataComponent {
    using ValuesType = std::vector<ValueType>;
    using IteratorType = typename std::vector<ValueType>::reverse_iterator;

public:
    DynamicDataComponent()
    {
        values.push_back(0);
        values.push_back(1);
        values.push_back(2);
        values.push_back(3);
    }

    const IteratorType getRBeginIt() const {
        return values.rbegin();
    }

private:
    ValuesType values;
};

int main() {
    DynamicDataComponent<size_t> dataComponent;
    std::cout << *dataComponent.getRBeginIt() << "\n";
}
Run Code Online (Sandbox Code Playgroud)

c++ methods iterator constants const-iterator

0
推荐指数
1
解决办法
115
查看次数

C++派生模板类继承自模板基类,不能调用基类构造函数

我试图从基类(模板)继承,派生类也是模板,它们具有相同的类型 T。我收到编译错误:非法成员初始化:'Base' 不是基类或成员...

为什么?如何调用基类构造函数?

#include <iostream>

template<class T>
class Base {
public:
    Base(T a) {
        std::cout << "A: " << a << std::endl;
    }
};

template<class T>
class Derived : public Base<T> {
public:
    Derived(T a) :
        Base(a) // this is the problem
    {}
};

int main() {
    int a = 1;
    Derived<int> derived(a);
}
Run Code Online (Sandbox Code Playgroud)

c++ inheritance templates constructor

-1
推荐指数
1
解决办法
290
查看次数