我正在使用 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/