当前位置导航:炫浪网>>网络学院>>编程开发>>C++教程>>C++进阶与实例

c++中的引用的使用原理和使用实例 (3)

写到这里已经写了很多了,一个下午吧。

问题弄好了我就想继续更改程序,是程序按照我的设想运行:

第一可以不用引用不?

可以用指针,不过相应的地方要改:

StringBad::StringBad(const StringBad *st)
{
    num_strings++;
 len = st->len;                  // set size
    str = new char[len + 1];          // allot storage
    strcpy(str, st->str);                   // initialize pointer
                       // set object count
    cout << num_strings << \": \\\"\" << str
         << \"\\\" object created\\n\";    // For Your Information
}

这个是显示构造函数。

改头文件,再改main中的传值,由于

void callme2(StringBad sb)
{
    cout << \"String passed by value:\\n\";
    cout << \"    \\\"\" << sb << \"\\\"\\n\";
}

因为上面对复制构造函数使用的是指针,如果仍旧用传值,sb=headline2也就是sb=StringBad::StringBad(headline2),指针要求的是 sb=StringBad::StringBad(&headline2),也就是说这个复制构造函数跟没有一样,是问题简单化就这样吧,void callme2(StringBad sb)编程void callme2(StringBad &sb),用引用!

改过之后的main程序是:

 // vegnews.cpp -- using new and delete with classes
// compile with strngbad.cpp
#include <iostream>
using std::cout;

#include \"stringbad.h\"

void callme1(StringBad &);  // pass by reference
void callme2(StringBad &);    // pass by value

int main()
{
    using std::endl;
    StringBad headline1=StringBad::StringBad(\"Celery Stalks at Midnight\");
    StringBad headline2(\"Lettuce Prey\");
    StringBad sports(\"Spinach Leaves Bowl for Dollars\");
    cout << \"headline1: \" << headline1 << endl;
    cout << \"headline2: \" << headline2 << endl;
    cout << \"sports: \" << sports << endl;
    callme1(headline1);
    cout << \"headline1: \" << headline1 << endl;
    callme2(headline2);
    cout << \"headline2: \" << headline2 << endl;[Page]
    cout << \"Initialize one object to another:\\n\";
    StringBad sailor =StringBad::StringBad(&sports);
    cout << \"sailor: \" << sailor << endl;
    cout << \"Assign one object to another:\\n\";
    StringBad knot;
    knot = headline1;
    cout << \"knot: \" << knot << endl; 
    cout << \"End of main()\\n\";
   
    return 0;
}

void callme1(StringBad & rsb)
{
    cout << \"String passed by reference:\\n\";
    cout << \"    \\\"\" << rsb << \"\\\"\\n\";
}

void callme2(StringBad &sb)
{
    cout << \"String passed by value:\\n\";
    cout << \"    \\\"\" << sb << \"\\\"\\n\";
}

另一个源文件是:

// strngbad.cpp -- StringBad class methods
#include <string.h>                    // string.h for some
#include \"stringbad.h\"
//using std::cout;
using namespace std;

// initializing static class member
int StringBad::num_strings = 0;

// class methods

// construct StringBad from C string
StringBad::StringBad(const char * s)
{
    len = strlen(s);                  // set size
    str = new char[len + 1];          // allot storage
    strcpy(str, s);                   // initialize pointer
    num_strings++;                    // set object count
    cout << num_strings << \": \\\"\" << str
         << \"\\\" object created\\n\";    // For Your Information

共3页 首页 上一页 1 2 3 下一页 尾页 跳转到
相关内容
赞助商链接