c++ - 类(class)传承与友元项目

标签 c++ class inheritance friend access-control

我偶然发现了一个在我看来非常有趣的问题。我不是要解决这个问题,只是建议如何继续我的代码,我想知道派生类是否继承了基类的 friend 。

问题是:

Class matrix, friend of class array is the base class for the class diagonal_matrix. The derived class must contain a parameterized constructor through which to highlight the transmission of parameters towards the constructor from the base class, destructor and a method to check if the matrix is square and diagonal ( all elements other than the ones from the principal diagonal are equal to zero). Illustrate the concept of virtual function (pure if it's more natural in implementation).

这是我到目前为止写的(今天关于如何继续不是很有创意):

#include <iostream>

using namespace std;

class arry
{
private:
    int *vec;
    int n;
public:
    int i,nrelem;
    arry(){};
    ~arry();
    void readArray(int);

};
arry::~arry()
{
    n=0;
    delete [] vec;
}
void arry::readArray(int elem)
 {
    n=elem;
    vec=new int[n];
   for(i=1;i<=elem;i++)
   {
       cout<<"vec["<<i<<"]=";
       cin>>vec[i];
   }
}

class matrix
{
public:
    friend class arry;
    matrix(int , int);
    ~matrix();
    };

int main()
{
    return 0;
} 

最佳答案

friend of class array is the base class for the class diagonal_matrix

array 没有 friend 。 array 类是 matrix 类的 friend ,因为它是 matrix 声明的

class matrix
{
public:
    friend class arry;  // this is my friend
    matrix(int , int);
    ~matrix();
};

你要求

advices on how to continue with my code

从在 array 类中声明友元开始。

and I'd like to know if derived classes inherit the friends of the base class

如果基类将 class A 声明为友元,则它不是派生类的友元,除非该派生类也将 class A 声明为友元。

C++ 标准 n3337 § 11.3/10 friend

Friendship is neither inherited nor transitive.

关于c++ - 类(class)传承与友元项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23920931/

相关文章:

c++ - 从 C++ 代码调用 Tiny C 编译器

C#:尝试在不同类中使用控制元素 - "object reference is required"

python - 直接调用时返回值的实例(不是实例)

c++ - 如何使用基类的接口(interface)?

Java:为什么通过将子类保存为父类,子类的属性会变成父类的默认值?

c++ - 在 C++ 中使用 void* 结构的内存分配

c++ - 是否有任何 GTKmm 版本编译标志?

c++ - 链接硬编码函数指针

php - 在当前命名空间之前的命名空间

javascript - JS 流 : Is inheritance in Flow broken?