Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 运算符C+的重载不明确+;_C++_Templates_Constructor_Type Conversion_Operator Overloading - Fatal编程技术网

C++ 运算符C+的重载不明确+;

C++ 运算符C+的重载不明确+;,c++,templates,constructor,type-conversion,operator-overloading,C++,Templates,Constructor,Type Conversion,Operator Overloading,一种方法是为每个操作符使用模板(+、-、*、/、点积等),但这不是很方便,因为我必须为每个操作符编写模板 这个问题有更好的解决办法吗?我想调用x-StringNum(3)。谢谢。您可以将构造函数和转换显式地转换为int 编译器不再在这些类型之间进行隐式转换,但您仍然可以这样使用它们 auto-stringNum=stringNum{3}//int到StringNum int y=静态_转换(stringNum); 与您的问题无关,但请花些时间阅读@Someprogrammerdude,我只在单文

一种方法是为每个操作符使用模板(+、-、*、/、点积等),但这不是很方便,因为我必须为每个操作符编写模板


这个问题有更好的解决办法吗?我想调用
x-StringNum(3)。
谢谢。

您可以将构造函数和转换显式地转换为int

编译器不再在这些类型之间进行隐式转换,但您仍然可以这样使用它们

auto-stringNum=stringNum{3}//int到StringNum
int y=静态_转换(stringNum);

与您的问题无关,但请花些时间阅读@Someprogrammerdude,我只在单文件程序中这么做:D,这样就不会有问题了#包括,使用名称空间std;只在比赛中使用,除非我(和其他人)尝试用另一个编译器编译你的程序,否则不起作用。为你节省了10秒,为试图帮助你的人浪费了数小时。我已经编辑了我的帖子。谢谢。但是这样做就没有了:int res=x-2(无显式转换的计算)。@HuyĐứ你应该在问题中提到你想做什么
x-2
仍然可以使用内置的
-
@HuyĐứcLê在这里添加
explicit
主要取决于您真正想要实现的目标,但通常将其添加到单参数构造函数是一种良好的做法,因为它会禁用可能发生的意外转换。它起到了作用。答案是使构造函数显式。谢谢你的帮助。
#include <iostream>
using namespace std;

class StringNum {
public:
    string s;
    StringNum() {s = "";}
public:
    StringNum(int n) {
        for (int i=1; i<=n; i++) s += "x";

    }

    operator int () {
        return s.length();
    }

    StringNum operator - (StringNum v) {
        int len = s.length() - v.s.length();
        StringNum res;
        for (int i=1;i<=len;i++) res.s += "x";
        return res;
    }

    /* // long solution. But this will allow the program to run.
    template <class T>
    StringNum operator - (T value) {
        return (*this) - StringNum(value);
    }
    */
};

int main()
{
    StringNum x(4);
    cout << 3 - x; // this compiles
    cout << x - 3; // error: ambiguous overload for operator - 
                   // change the program so that the 2nd line output 2
    return 0;
}
In function 'int main()':|
error: ambiguous overload for 'operator-' (operand types are 'StringNum' and 'int')|
note: candidate: operator-(int, int) <built-in>|
note: candidate: StringNum StringNum::operator-(StringNum)|
a) int(x) - 3
b) x - StringNum(3)