【问题标题】:How to make comparator for qsort so that it could compare private members?如何为 qsort 制作比较器以便它可以比较私有成员?
【发布时间】:2021-07-17 23:42:31
【问题描述】:

我在基类中有一个受保护的数组

#pragma once
#ifndef BASE_H
#define BASE_H
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

class Base {
protected:
    int N;
    int array[100];
    friend int compare(const void*, const void*);
};
#endif

而且我需要在派生类中对其进行排序

#include "Derived2.h"

int compare(const void* arg1, const void* arg2)
{
    return (*(int*)arg1 - *(int*)arg2);
}
void Derived2::array_sort() {
    qsort (array, N, sizeof(int), compare);
}

派生的.h:

#pragma once
#ifndef DERIVED2_H
#define DERIVED2_H
#include "Base.h"

class Derived2 : public Base {
public:
    void array_sort();
    void array_output();
    friend int compare(const void*, const void*);
};
#endif

但是我遇到了访问冲突错误。 error screenshot (我认为,我的“比较”函数不允许读取基类的受保护字段)

我什至尝试让函数“比较”基类和派生类的朋友,它仍然不起作用,我得到了同样的错误。 如果我尝试让函数比较派生类方法,则项目根本无法编译。 如何解决?

【问题讨论】:

  • 在 C++ 中你有std::sort,你为什么不使用它呢?花几周时间阅读更多关于programming in C++ 的信息。使用GCC 编译您的代码,调用为g++ -Wall -Wextra -g,并从RefPerSys 和其他开源C++ 项目中汲取灵感。
  • @Basile Starynkevitch 我不能使用 ,它必须是一个数组
  • @Cognosce "it still doesn't work." 是一个非常模糊的问题描述,考虑到您被告知应该发布一个清晰简洁的问题描述,或者你发帖的时候不是吗?您可以阅读如何创建minimal reproducible exampleedit 相应的问题!
  • 那么你可以使用std::array,你当然应该在ninjaFLTKRefPerSysfish等C++项目的源代码中寻找灵感
  • @Cognosce — std::sort 在 C 样式数组上工作得很好。

标签: c++ oop qsort


【解决方案1】:

访问冲突与 C++ 类成员访问模式无关。它表明您的代码在未分配的内存位置读取或写入(即越界访问)。目前尚不清楚是什么原因造成的,但我的猜测是Base::N 的值大于 100,即Base::array 的大小。检查您是否正确初始化它(您发布的代码没有)。

另外,正如其他人已经推荐的那样,没有理由在 C++ 中使用 qsort,因为 std::sort 会更高效和安全。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-09-08
  • 2012-06-04
  • 2014-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 2015-05-22
相关资源
最近更新 更多