首页 文章

C简单的cout ostream

提问于
浏览
2
#include"MyString.h"
#include<iostream>
    MyString::MyString()//default constructor
    {
        length=0;
        data=NULL;
        cout<<"Default called by right none is called"<<endl;
        system("pause");
    }
    MyString::MyString(char *source)//cstyle string parameter
    {
        int counter=0;
        //we implement count without using getlen
        for(int i=0;(source[i])!='\0';i++)//assume their char string is terminated by null
        {
            counter++;
        }
        length=counter;
        cout<<"THE LENGTH of "<<source<<" is "<<counter<<endl;
        system("pause");
        data = new char[length];
    }
    void MyString::print(ostream a)//what to put in besides ostream
    {
        a<<data;
    }

以上是我的实现文件

这是我的主文件

int main()
 {
    MyString s1("abcd");// constructor with cstyle style array
    s1.print(cout);
    system("pause");
    return 0;
 }

为什么不能这样做?我得到这个错误

错误C2248:'std :: basic_ios <_Elem,_Traits> :: basic_ios':无法访问类'std :: basic_ios <_Elem,_Traits>'中声明的私有成员

百万谢谢!错误固定!!

2 回答

  • 2

    原因是对 print 的调用尝试复制输出流,这是不允许的 . 您已更改函数以将参数作为参考:

    void MyString::print(ostream &a)
    
  • 2

    您不能复制 std::coutstd::cinstd::cerr 或从 std::ios_base 派生的任何其他对象,因为该对象的复制构造函数是私有的...您必须通过引用传递从 ios_base 派生的所有流对象,以防止调用拷贝构造函数 . 这样你的功能签名:

    void MyString::print(ostream a);
    

    需要至少改变

    void MyString::print(ostream& a);
    

相关问题