+ -
当前位置:首页 → 问答吧 → 形参是T类型引用(T &), 实参是否应该接受可以转到到T类型的B类型?

形参是T类型引用(T &), 实参是否应该接受可以转到到T类型的B类型?

时间:2010-09-04

来源:互联网

本帖最后由 wonderbeyond 于 2010-09-05 10:38 编辑

形参是T类型引用(T &), 实参是否应该接受可以转到到T类型的B类型?

测试平台 UBUNTU 10.04; Linux 2.6.32-24-generic; gcc version 4.4.3

[首先是非const引用的情况]
如函数 void f(string s) 可以接受char*实参自然没问题, char* 可以转换到 string类型.
但给函数void f(string &s)传递char*实参是我犯过的错误, 但我对编译器拒绝编译表示理解.
因为参数明确表示需要string的引用, 虽然可以创建一个由char*转换来的string类型的临时
对象, 但是临时对象只有被复制才有意义, 它会马上消失的, 所以引用没有意义了. 作为验证,
我手动做了这个工作, 我以 f(string(argv[1])) 调用 void f(string &s) 函数, 其中argv[1]是
char*指针, 结果编译器说:
invalid initialization of non-const reference of type ‘std::string&’ from a temporary of type ‘std::string’

[实参是const引用的情况]
到此, 似乎我没有说什么, 但是当我把普通引用换成const引用时试验, 编译器的表现让我很不解!
如函数 void f(const string &s), 给它传递 char* 参数能顺利编译并正确运行, 同时以临时
的string对象调用它是表现正常...

我已经迷茫了... C++还有多少技术细节我没了解? 我在C++ primer没有发现这方面的技术
细节... 我感觉有点陷入泥潭了...
希望达人解释...
谢谢!!!

作者: wonderbeyond   发布时间: 2010-09-04

本帖最后由 wonderbeyond 于 2010-09-05 17:53 编辑

好象没人甩我啊!
为了让大家知道我在说什么, 我准备了两个示例程序:

<一>
#include <iostream>
#include <string>

using namespace std;

class Type {
public:
    Type(const string& s) : data(s) { cout << "Type() called\n"; }
    ~Type() { cout << "~Type() called\n"; }
    const string& get() const {return data;}
private:
    string data;
};

void f(Type& t)
{ cout << t.get() << endl; }

int main(int argc, char** argv)
{
    string s(argv[1]);
    f(s);
    return 0;
}
///////////////////////////////////////////////////////////////////
以上程序不能编译, 函数f()形参是 Type&, 而实参是string(当然string可以转换到Type型), 让我不解的是把f()的形参改为const 引用,就可以顺利编译并执行了, 见示例二.

<二>
#include <iostream>
#include <string>

using namespace std;

class Type {
public:
    Type(const string& s) : data(s) { cout << "Type() called\n"; }
    ~Type() { cout << "~Type() called\n"; }
    const string& get() const {return data;}
private:
    string data;
};

void f(const Type& t)
{ cout << t.get() << endl; }

int main(int argc, char** argv)
{
    string s(argv[1]);
    f(s);
    return 0;
}
////////////////////////////////////////////////////////////////////////////

附件:
示例<一>的编译错误输出:
test.cc: In function ‘int main(int, char**)’:
test.cc:21: error: invalid initialization of reference of type ‘Type&’ from expression of type ‘std::string’
test.cc:15: error: in passing argument 1 of ‘void f(Type&)’

作者: wonderbeyond   发布时间: 2010-09-05

相关阅读 更多