c++ - 如何区分 char 文字和 unsigned int 作为构造函数的参数

标签 c++ constructor char unsigned

我的代码有 2 个不同的构造函数,一个只有一个 unsigned 作为参数,另一个有一个 char 和一个 unsigned,其中 unsigned 有一个默认值。

Myclass::Myclass(unsigned);
Myclass::Myclass(const char, unsigned = 1);

问题是当我尝试以下操作时:

Myclass a = 'A';

调用了只有无符号参数的构造函数(在本例中为 65)

在这种情况下如何调用第二个构造函数? 我也不希望 0-255 之间的值仅被解释为 Ascii 值。

编辑:

显示错误的示例代码:

标题:

#ifndef Myclass_H_
#define Myclass_H_

class Myclass {
public:
    Myclass(unsigned int = 10);
    Myclass(const char*);
    Myclass(char , unsigned int= 10);
    Myclass(const Myclass&);
    virtual ~Myclass();
};

#endif /* Myclass_H_ */

类主体:

#include "Myclass.h"
#include <iostream>

using namespace std;

Myclass::Myclass(unsigned int)
{
    cout << "unsigned" << endl;
}
Myclass::Myclass(const char*)
{
    cout << "pointer" << endl;
}
Myclass::Myclass(char , unsigned int)
{
    cout << "char" << endl;
}
Myclass::Myclass(const Myclass&)
{
    cout << "copy" << endl;
}
Myclass::~Myclass(){}

int main()
{
    Myclass a = 'A';
    return 0;
}

在控制台中显示“未签名”。

最佳答案

我无法复制您声称的问题。我使用以下测试代码进行了快速检查:

#include <iostream>

struct foo {
    foo(const char, unsigned = 1) { std::cout << "Foo(char, unsigned)"; }
    foo(unsigned) {
        std::cout << "Foo(unsigned)";
    }
};

int main() {
    foo f = 'A';
}

...以及我手边的编译器(VC++ 2013、VC++ 2015、g++ 4.8、g++5.2),foo(char, unsigned) 总是被选中的那个(哪个正如我所料)。

您使用什么编译器为该输入选择其他重载?我希望这来自真正古老的编译器(遵循 C 规则,其中字 rune 字具有类型 int 而不是类型 char),但这些已经过时了几十年。

关于c++ - 如何区分 char 文字和 unsigned int 作为构造函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34051376/

相关文章:

c - 在 C 的 char 数组中存储一个整数

c++ - 爬楼梯动态规划的最小成本

java - 从静态类型到动态类型

c++ - 访问私有(private)构造函数 C++

matlab - 在MATLAB中将stringptrptr参数传递给C-DLL函数foo(char **)-清除指针会使MATLAB崩溃

c - 跳过中间的一些 scanf

c++ - g++ 默认启用 sse2 吗?

c++ - Visual Studio 未找到与解决方案相关的 NuGet 包

C++:类和构造函数:使用初始化列表来初始化字段

java - 在java中初始化final字段