c++ - 将私有(private)对象变量与用户输入的变量进行比较

标签 c++

我已经重载了 >><<.dat 中提取信息的运算 rune 件并将其写入对象。

是否可以访问 postalCode不使用访问器的变量,例如 getPostalCode();并且不转换 postalCode公开?理想情况下使用重载运算符之一。

我可以重写提供的任何代码,但希望尽可能避免添加访问函数。

我们让用户输入邮政编码,程序需要在搜索提供的 .dat 文件后返回所有具有匹配邮政编码的地址。

我避免使用访问器,因为针对特定作业的问题是如何措辞的。

class Address{
    public:
        void set();
        void input();
        void output();


    Address(){
        streetName = "";
        streetNr = 0;
        city = "";
        postalCode = "0000";
    }

    private:
        string streetName;
        int streetNr;
        string city;
        string postalCode;
        friend istream & operator>>(istream & in, Address & address);
        friend ostream & operator<<(ostream & out, Address & address);

};

ostream & operator<<(ostream & out, Address & address){
    out << address.streetNr << " " << address.streetName << endl;
    out << address.city << endl;
    out << address.postalCode << endl;
    out << endl;

    return out;
}

istream & operator>>(istream & in, Address & address){
    getline(in >> ws, address.streetName, '\n');
    in >> address.streetNr;
    getline(in >> ws, address.city);
    in >> address.postalCode;   

    return in;
}

int main(){

    Address temp, addresses [20];
    string pCode;
    int i = 0;

    in.open("Address.dat");
    if (in.fail()){
        cout << "Input file opening failed. \n" << endl;
        exit(1);
    }

    cout << "Postal code: ";
    cin >> pCode;
    cout << endl;

    while (in >> temp){
        if (temp.getPostalCode() == pCode){
            addresses[i] = temp;
            i++;
        }
    }

我了解访问 postalCode直接访问是不可能的,因为它将无法访问。

最佳答案

Is it possible to access the postalCode variable without the use of an accessor such as getPostalCode(); and without converting postalCode to public?

不,你不能。数据成员是私有(private)的,不使用成员函数(或友元函数)就无法从外部访问它。重载运算符算作一个函数。

Ideally using one of the overloaded operators.

好吧,如果重载运算符不算作“访问器”,那么从技术上讲,您可以滥用重载运算符来访问成员。例如,这样做是符合标准的:(在类中)

bool operator==(const std::string& code) const noexcept
{
    return postalCode == code;
}

然后你可以替换

temp == code

对于 temp.getPostalCode() == code。这是非常违反直觉的,并且远不如使用描述性函数名称。赋予重载运算符奇怪的语义被认为是极其糟糕的做法,因为它的唯一目的是混淆代码。

关于c++ - 将私有(private)对象变量与用户输入的变量进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57920481/

相关文章:

c++ - 不允许非类型参数的部分模板特化

c++ - helib 什么时候需要引导?

c++ - (C++) 编译时自动生成switch语句case

c++ - 在 C++ 项目中使用 (OSX) Core MIDI

c++ - 对话框单位到屏幕坐标

c++ - 带有 is_enum 的 enable_if 不起作用

c++ - 从源构建 mongodb 时出错

c++ - 如何在一定数量的小数位后截断 float (不四舍五入)?

c# - 使用 C++/MFC 和 C# 中的插件扩展 C++/MFC 应用程序

c++ - C++11中列表初始化的优点