超载运营商=? C ++

时间:2018-05-03 16:40:11

标签: c++ char operator-overloading

我在尝试将我创建的类中的对象插入到char时遇到了麻烦。我创建了一个类名称Element作为更大程序的一部分,但是当我尝试重载operator =以便我可以获得char变量时我在Element obj中获得的char没有任何工作...

element.h展开

class Element {

private:
    char val;
public:
    Element();
    Element(char newVal); //check input - throw execption
    ~Element();

friend ostream& operator<<(ostream& os, const Element& obj);
void setElement(char newVal);
char getElement();

void operator= (const Element newVal);
void operator= (char newVal);


};

Element.cpp

#include "Element.h"



Element::Element()
{
    val ='.';
}

Element::Element(char newVal)
{
    if (newVal!='X' && newVal!='O'&& newVal!='.'){
        inputExecption error;
        error.what();
    } else{
        val=newVal;
    }
}

Element::~Element()
{

}

void Element::setElement(char newVal)
{
    if (newVal!='X' && newVal!='O'&& newVal!='.'){
        inputExecption error;
        error.what();
    } else{
        val=newVal;
    }
}

char Element::getElement()
{
    return val;
}

ostream& operator<<(ostream& os, const Element& obj)
{

    return os << obj.val;

}

void Element::operator= (const Element Value){
    val = Value.val;
}

void Element::operator= (char newVal){
    if(val != 'X' && val != 'O'){
        inputExecption a;
        a.what();
    }
    val = newVal;
}


正如我所说,我想做的是:

Element x='X';
char c = x; //(c=x.val)
cout<<c<<endl;//Will print X

THX! :)

2 个答案:

答案 0 :(得分:5)

换句话说,您尝试将Element类型的对象转换为char类型的对象。您可以使用转换运算符:

class Element {
  // ...
  operator char() const { return val; }
};

赋值运算符仅在赋值左侧使用Element的实例时才有效。

答案 1 :(得分:2)

恕我直言,编写隐式转换运算符(建议为0x499602D2)

例如,假设您有两个单独的文件:

//File char_utils.hh
#include <iostream>
void accept(char character) { std::cout <<"character: " <<character <<'\n'; }


//File elements_utils.hh
#include <iostream>
void accept(Element const& element) {
    std::cout <<"element.getVal(): " <<element.getVal() <<'\n';
}

然后,根据您在实现文件中包含的内容(char_utils.hhelements_utils.hh),您将获得不同的行为,这可能会导致许多微妙的错误和/或有趣的行为。 ;)

这可以通过声明转换运算符explicit来克服,即

explicit operator char() const { return val; }

在这种情况下,你只需要:

Element e{'x'};
char c = static_cast<char>(e);

更清楚地显示了意图。

但是,为什么你需要使用隐式转换呢?特别是当你可以使用Element::getElement()时?如果我建议,我会使用不同的namin,例如Element::getValue()Element::getElement() 非常令人困惑。

进一步阅读:https://stackoverflow.com/a/16615725/1877420