Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        3年前关闭。
                                                                                            
                
        
好的,我的问题在这里很简单..我想为不同的值类型构造一个getter和setter方法。

#include <iostream>;

class Vectors {
public:
    Vectors() {};
    Vectors(int a, int b) {
        x = a, y = b;
    }
    int getX() {
        return x;
    }
    int getY() {
        return y;
    }
    float getX() {
        return (float)x;
    }
    float getY() {
        return (float) y;
    }
     friend Vectors operator+(const Vectors& v1, const Vectors& v2);
     friend Vectors operator/(const Vectors& v1, const Vectors& v2);
protected:
    int x, y;
private:

};

Vectors operator+(const Vectors& v1, const Vectors& v2) {
    Vectors brandNew;
    brandNew.x = v1.x + v2.x;
    brandNew.y = v1.y + v2.y;
    return (brandNew);
};

Vectors operator/(const Vectors& v1, const Vectors& v2) {
    Vectors brandNew(v1.x / v2.x, v1.y/v2.y);
    return brandNew;
}

int main() {
    Vectors v1(2, 3);
    Vectors v2(4, 5);
    Vectors v3;
    v3 = v1 + v2;
    Vectors v4 = v1 / v2;

    std::cout << "VECTOR 4 X : " << v4.getX() << std::endl;
    std::cout << "VECTOR 4 Y : " << v4.getY() << std::endl;

    std::cout << "Vector V3 X : " << v3.getX() << std::endl;
    std::cout << "VECTOR V3 Y : " << v3.getX() << std::endl;
}


但是显然,它说不能做函数重载,唯一的区别是返回类型。

最佳答案

如果不更改我所知道的参数,就无法重载函数。您需要更改函数名称(将其命名为getXFloat()或其他名称),或者仅在调用函数后将其更改为强制转换,例如:

float the_x_value = static_cast<float>(vec.getX());


我会选择第二种选择。

关于c++ - Getters和Setters C++ ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36782438/

10-11 01:04