c++ - 如何强制不在 C++ 中使用转换构造函数

标签 c++ operator-overloading

我正在处理一个包含矩阵的项目,但我遇到了重载运算符的问题。

我已经声明了这些用户友好的输入/输出函数:

friend std::istream& operator>>(std::istream& is, MathMatrix& m); //keyboard input
friend std::ostream& operator<<(std::ostream& os, const MathMatrix& m); // screen output
friend std::ifstream& operator>>(std::ifstream& ifs, MathMatrix& m); // file input
friend std::ofstream& operator<<(std::ofstream& ofs, const MathMatrix& m); // file output

在定义最后一个时,在这段简单的代码中,出现错误且无法编译:

// file output
std::ofstream& operator<<(std::ofstream& ofs, const MathMatrix& m) {
    //put matrix dimension in first line
    ofs << m.n << std::endl;
    //put data in third line
    for (int i=0; i<m.n; i++) {
        for (int j=0; j<m.n; j++) ofs << m(i,j) << " ";
        ofs << std::endl;
    }
    return ofs;
}

错误在 ofs << m.n 中(与 ofs << m(i,j) 中的类似)。它说:

const MathMatrix &m
Error: more than one operator "<<" matches these operands:
    function "operator<<(std::ofstream &ofs, const MathMatrix &m)"
    function "std::basic_ostream<_Elem, _Traits>::operator<<(int _Val) [with _Elem=char, _Traits=std::char_traits<char>]"
    operand types are std::ofstream << const int

过了一会儿我想也许问题是我有一个 MathMatrixMathMatrix (int n) 这样的构造函数,因此编译器可能会尝试从 int n 进行转换至 MathMatrix(int n) .我不明白为什么会那样做,但考虑到 IDE 给出的解释,这是我能想到的唯一解释。

你能看出我错过了什么吗?你知道怎么解决吗?

最佳答案

如果在你的类中你有一个构造函数,它的单个参数的类型与你的类不同,它可以用于隐式类型转换。为了防止这种情况,您只需要显式标记该构造函数:

class MathMatrix {
public:
   explicit MathMatrix( int m );
...
};

始终将单个参数构造函数标记为显式是个好主意(除非参数是相同的类类型或者您确实希望进行此类类型转换)

关于c++ - 如何强制不在 C++ 中使用转换构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19433014/

相关文章:

关于加法运算符重载的 C++ 问题

c++ - directory_entry 的输出与具有变体的类的重载 ostream 运算符<< 冲突

c++ - 类模板上的运算符重载

haskell - 有没有办法在ghc中重载并置?

c++ - 按名称调用父类中的子类方法

c++ - LeapMotion、Qt 和信号

c++ - 指向类方法错误的指针数组 C++11

c++ - 删除文件中的空行

c++ - 需要指针的私有(private)类变量?

python - 为什么 str 不能得到第二个参数,而 __str__ 可以?