c++ - 转换问题

标签 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;
}

编译产量:

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

但是有 c-tor 接收 const char *。

UDP:

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

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)’

如果我使用 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)’

最佳答案

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

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

关于c++ - 转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1663241/

相关文章:

c# - 分号在 C# 中的条件 block 之后做什么?

c - MinGW找不到源文件

c++ - C++11 可变参数模板中的 va_arg() 是什么?

c++ - 为什么我可以在 MSVC 和 icc 中为 glm::vec 创建用户定义的结构化绑定(bind),但不能在 Clang 和 GCC 中创建?

Python 编译错误 : "LONG_BIT definition appears wrong for platform"

C编程; GCC 在运行时崩溃

ubuntu - 如何构建 glibc 包的数学库?

c++ - 让公共(public)成员变量访问 C++ 中同一类的私有(private)成员

c++ - 是否可以将 C++ 共享库加载到 Mathematica 8.0?

c++ - 涉及 `crti.o` 和 `crt1.o` 的奇怪链接器错误