转换问题

dim*_*mba 1 c++ gcc compilation

我正在使用gcc 4.3.2.

我有以下代码(简化):

#include <cstdlib>

template<int SIZE>
class Buffer
{
public:
    explicit Buffer(const char *p = NULL) {}
    explicit Buffer(const Buffer &other);

    const char *c_str() const { return m_buffer; }

private:
    char m_buffer[SIZE];
};

typedef Buffer<10> A;
typedef Buffer<20> B;

void Foo(A a) {
}

int main()
{
    B b;
    Foo(b.c_str());  // line 25 fails compilation
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

编译产量:

test.cpp: In function ‘int main()’:
test.cpp:25: error: conversion from ‘const char*’ to non-scalar type ‘A’ requested
Run Code Online (Sandbox Code Playgroud)

但是有接收const char*的c-tor.

UDP:

如果我从第一个c-tor中删除了我收到的

test.cpp: In function ‘int main()’:
test.cpp:25: error: no matching function for call to ‘Buffer<10>::Buffer(A)’
test.cpp:7: note: candidates are: Buffer<SIZE>::Buffer(const char*) [with int SIZE = 10]
test.cpp:25: error:   initializing argument 1 of ‘void Foo(A)’
Run Code Online (Sandbox Code Playgroud)

如果我使用Foo(A(b.c_str()))我收到:

test.cpp: In function ‘int main()’:
test.cpp:25: error: no matching function for call to ‘Buffer<10>::Buffer(A)’
test.cpp:25: error:   initializing argument 1 of ‘void Foo(A)’
Run Code Online (Sandbox Code Playgroud)

AnT*_*AnT 13

您的转换构造函数已声明explicit.关键字explicit专门用于防止该构造函数的隐式转换.隐式转换正是您期望在代码中发生的(在Foo调用时).

explicit如果您希望它在隐式转换中工作,为什么要声明构造函数?

  • @idimba:你正在将`const char*`传递给一个期望`A`的函数.`const char*`不是'A`,因此需要进行转换.但是编译器不能使用`A :: A(const char*)`转换构造函数,因为它被声明为`explicit`.如果你想要使用这个构造函数,你必须拼出一个显式转换`Foo(A(b.c_str()))` (2认同)