c++ - 运算符 << 和继承/组合

标签 c++ overloading operator-keyword

我发现自己在尝试正确重载 operator<< 时遇到了一些麻烦。我已经搜索了其他关于它的问题,但似乎没有一个答案适合这个问题,所以这里是: 我有一个类(Register)存储另一个类(Film 的子类,它是抽象的)的样本。 Register 的重载运算符 << 应该通过 ostream 类将存储在每个 Film 类型元素中的所有数据放在屏幕上。代码如下:

class Register{                                             
    private:
    int elementNum;
    Film* pData;
    };
    ostream &operator<<(ostream & os,const Register &v);

这些在标题中,运算符 << 在 cpp 中:

ostream &operator<<(ostream & os,const Register &v){
    for(int i=0;i<v.elementNum;i++){
os<<v.pData[i].print()<<endl;
}
return os;
    }

问题是,这样我就无法访问寄存器的私有(private)变量。所以我尝试将重载的 operator<< 作为 Register 的成员,但随后编译器告诉我该函数必须只有一个参数。最后,如果我从参数中删除 ostream& os,它会告诉我该函数需要两个参数。所以我会对一种解决方案感兴趣,其中存储在 pData 中的信息可以通过运算符 << 有效地显示在屏幕上。提前致谢!

最佳答案

你必须申报operator<<作为 friend 访问Register必须授予实现(私有(private)数据):

class Register{                                             
    private:
    //...
    friend std::ostream &operator<<( std::ostream & os,const Register &v);
};

std::ostream &operator<<( std::ostream & os,const Register &v) {
    for( int i=0; i<v.elementNum; i++){
        os << v.pData[i].print() << std::endl;
    }
    return os;
}

friend 函数可以访问声明 friend 的类的所有私有(private)(以及 protected 和公共(public))数据。

C++ 标准 n3337 § 11.3/1 说

friend

A friend of a class is a function or class that is given permission to use the private and protected member names from the class. A class specifies its friends, if any, by way of friend declarations. Such declarations give special access rights to the friends, but they do not make the nominated friends members of the befriending class.

§ 11.3/2

Declaring a class to be a friend implies that the names of private and protected members from the class granting friendship can be accessed in the base-specifiers and member declarations of the befriended class.

关于c++ - 运算符 << 和继承/组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23687741/

相关文章:

java - 静态导入重载方法

c++ - 正则表达式匹配产生意外结果

C++ - 使用该方法的部分特化重载模板类方法

c++ - 包含 <vector> 时的奇怪行为

c++ - 以 const char* 作为参数的方法如何与以 const int& 为参数的方法接近匹配?

c++ - const char 和二进制运算符错误

sql-server - "&"运算符在transact sql中的使用

c++ - 重载二元运算的正确方法

c++ - 错误 : 'std::string_view' has not been declared

c# - 如何在 dll 项目中用 C++ 创建命名空间和构造函数?