c++ - 从析构函数访问模板类构造函数的参数,可以吗?

标签 c++ oop templates constructor destructor

我想看看如何从析构函数访问构造函数的参数。在此示例中,我想修改构造函数中的参数并在析构函数中恢复它。

template<typename T>
class sorted_array_view {
public:    
    sorted_array_view(T* givenArray,size_t size) {
         for( int idx = 0; idx < size; ++idx){
            data.push_back(givenArray[idx]);
            originaldata.push_back(givenArray[idx]);
         }
         std::sort(data.begin(), data.end());
         for(int idx =0; idx<size; ++idx){
            givenArray[idx] = data.at(idx);
         }
    }

    ~sorted_array_view(){
         for(int idx =0; idx<size; ++idx){
            givenArray[idx] = originaldata.at(idx);
         }
    }

private:
    std::vector<T> data;
    std::vector<T> originaldata;
};

但是我在析构函数中收到错误'givenArray' was not statements in this scope。我如何访问givenArray

最佳答案

只需使 givenArray 成为该类的数据成员即可。

然后析构函数(以及任何其他成员函数)将可以访问它。


PS:如果它们的值相同(这似乎是您的代码的情况),请将析构函数中的 size 更改为 originaldata.size() 。否则,您也需要 size 才能成为数据成员。

关于c++ - 从析构函数访问模板类构造函数的参数,可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51101267/

相关文章:

c++ - 尝试将字符串文字作为模板参数传递

c++ - 使用 Qt 和 C++ 连续绘制对象

c++ - 如何在 CMainFrame 中处理鼠标点击

php - 过程函数与静态方法。哪个更好或者两者都避免?

c++ - 将迭代器实现为具有引用语义的抽象生成器的正确方法

java - 模板匹配 mattoBitmap opencv for android

c++ - 在哪里实现容忍度来决定何时在 Qt 中检测触摸屏按下事件和移动事件?

c++ - 在循环中创建新的指针对象

php - 使用不同的参数调用 PHP 方法

oop - 单一责任原则有什么用?