c++ - 从 C++ 中的类成员函数返回对象

标签 c++ function object

上面代码中的任务是编写计算新点的成员函数,这是另外两个点的数量。而且我不知道如何返回对象或我应该做什么。这里是代码,功能用三个!!! 标记。该函数必须返回一些东西,我不能使它无效,因为不允许引用 void。

    class point {
    private:
        float x;
        float y;
    public:
        point();
        point(float xcoord, float ycoord);
        void print();
        float dist(point p1, point p2);
    !!! float &add(point p1, point p2);
        float  &X();
        float &Y();
        ~point();
    };
    float & point::X() { return x; }
    float & point::Y() { return y; }
    point::point() {
        cout << "Creating POINT (0,0)" << endl;
        x = y = 0.0;
    }
    point::point(float xcoord, float ycoord) {
        cout << "Creating POINt (" << xcoord << "," << ycoord << ")" << endl;
        x = xcoord;
        y = ycoord;
    }
    void point::print() {
        cout << "POINT (" << x << "," << y << ")";
    }
    float point::dist(point p1, point p2) {
        return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));
    }
   !!!// float & point::add(point p1, point p2) {
        point z;
        z.X() = p1.X() + p2.X();
        z.Y() = p1.Y() + p2.Y();
        z.print();
    }
    point::~point() {
        cout << "Deleting ";
        print();
        cout << endl;
    }
    int main() {
        point a(3, 4), b(10, 4);
        cout << "Distance between"; a.print();
        cout << " and "; b.print();
        cout << " is " << a.dist(a, b) << endl;
    }

我成功了!这是必须添加的功能

//prototype

    point &add(point& p1, point& p2);
//function itself

    point & point::add(point& p1, point& p2) {
        point z;
        z.x = p1.X() + p2.X();
        z.y = p1.Y() + p2.Y();
        z.print();
        return z;
    }

非常感谢 ForceBru!!还有你们所有人

最佳答案

做什么

您也可以返回一个:

point point::add(const point& p1, const point& p2) {
    point result;

    result.x = p1.x + p2.x;
    result.y = p1.y + p2.y;

    return result;
}

请注意,这里不需要使用 X()Y() 函数,因为此方法已经可以访问私有(private)成员。

也可以进行运算符重载

/*friend*/ point operator+ (const point& one, const point& two) {
    // the code is the same
}

如何使用

int main() {
    point one(2,5), two(3,6), three;

    three.add(one, two);

    std::cout << "Added " << one.print() << " and " << two.print();
    std::cout << " and got " << three.print() << std::endl;

    return 0;
}

编辑:如评论中所述,您不应返回对add 函数 中创建的对象的引用,因为在这种情况下,您只能返回对类成员和 static 变量的引用。

关于c++ - 从 C++ 中的类成员函数返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35059553/

相关文章:

multithreading - 增量数字表 postgresql 线程安全

C函数调用奇怪错误

python - 这个 "and"语句实际上在返回中做了什么?

java - 数组大小和 .length 的问题

javascript - 如何从类函数内部访问对象属性

c++ - 如何使用 Windows 获得(真实)鼠标位移

c++ - 声明指向字符串的动态指针数组时出现问题

C++模板类和继承

C++:涉及继承和 "using"时的方法重载

python - 如何将全局变量传递给另一个函数调用的函数