c++ - 类方法和参数传递

标签 c++ class methods

我一直在编程,并且在 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/

相关文章:

java - 如何正确设置变量以在 boolean 值中进行测试?

java - 如何清除单个字符串的不同部分,同时使结果成为字符串本身?

c++ - 如何重载 = 运算符以在 C++ 中通过引用进行复制?

C++ 类继承和赋值运算符

php - Laravel -- 为什么 `::class` 常量

java - hibernate 删除错误 : Batch Update Returned Unexpected Row Count

c++ - 为什么进程的 "Private Bytes"内存计数器永远不会返回到它的原始值?

非固定枚举的 C++11 值?

c++ - 使用可变参数模板计算元组大小时大小错误

c++ - 使用另一个类的静态成员函数时构造函数中的未解析静态符号。