我一直在编程,并且在 C++ 类中发现了奇怪的行为。所以我制作了一个简单的类,其中包含字符串、该类的构造函数和从对象打印字符串的 friend 方法(show)。但是正如您在 main 函数中看到的那样。我传递给方法(显示)简单的字符串并且它有效。 我发现它很方便,但是如果方法参数是对对象的引用,为什么它会起作用呢?
#include <iostream>
using namespace std;
class lol
{
char * str;
public:
lol(const char * s);
friend void show(const lol & l);
};
lol::lol(const char * s) //assign string to object
{
str = new char[strlen(s)+1];
strcpy(str,s);
}
void show(const lol & l) //prints string from object
{
cout << l.str;
};
int main()
{
show("TEST"); //passing string but not an object
return 0;
};
最佳答案
I found it convenient, but why it worked if method parameter is reference to an object?
之所以有效,是因为您的 lol
类定义了一个接受 const char*
的构造函数并且未标记为explicit
.
这授权编译器解析调用 show("TEST")
通过构建类型为 lol
的临时对象,传递字符串文字 "TEST"
作为构造函数的参数,并绑定(bind)您的引用参数 l
到这个临时对象。
为了防止这种隐式用户定义的转换序列,将您的构造函数标记为explicit
:
class lol
{
char * str;
public:
explicit lol(const char * s);
// ^^^^^^^^
friend void show(const lol & l);
};
这样,调用show("TEST")
will result in a compiler error .
关于c++ - 类方法和参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15690149/