【发布时间】: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 example 和edit 相应的问题!
-
@Cognosce —
std::sort在 C 样式数组上工作得很好。