简体   繁体   English

返回两个其他成员函数值的 C++ 成员函数

[英]C++ Member Function That Returns A Value of Two other member functions

I had this question on a test about a month ago and I still can't seem to understand it completely and quite frankly it's driving me crazy.大约一个月前,我在测试中遇到了这个问题,但我似乎仍然无法完全理解它,坦率地说,这让我发疯了。 I will include the question at the bottom.我将在底部包含这个问题。 But, it's asking to create a single parameter constructor that creates a new "Vector" (the name of the class) which is the sum of two others.但是,它要求创建一个单参数构造函数,该构造函数创建一个新的“Vector”(类的名称),它是另外两个的总和。 The vector class I made has a function set/get x and set/get y.我制作的向量类有一个函数 set/get x 和 set/get y。 My hang up is I can't seem to figure out how to make a function that adds the two x's and y's together from vector and vector1 to create a new Vector...call it vector2 .我的挂断是我似乎无法弄清楚如何制作一个函数,将vectorvector1的两个 x 和 y 相加,以创建一个新的 Vector...称之为vector2 I'll include everything I got so far.我将包括到目前为止我得到的一切。 Thanks to anyone willing to make it through the wall of text as confusing as it must be haha.感谢任何愿意让它通过文本墙的人,因为它必须是令人困惑的哈哈。

Write a class Vertor with the following properties and place the class in a separate header file :编写一个具有以下属性的类Vertor并将该类放在单独的头文件中:

Add member function with a single parameter of another vector and returns a new vector that is the sum of the two (to add vectors you sum the components, for example, Cx = Ax + Bx and Cy = Ay + By). Add具有另一个向量的单个参数的成员函数,并返回一个新向量,该向量是两者之和(要添加向量,您可以对分量求和,例如,Cx = Ax + Bx 和 Cy = Ay + By)。

Write a program that includes the Vector header file, constructs two different vectors and demonstrates the magnitude, angle, and add functions.编写一个包含 Vector 头文件的程序,构造两个不同的向量并演示大小、角度和相加函数。

Data Members数据成员
vector向量
x component x分量
y component y 分量
Member Functions成员函数
Set and Get functions for all data members设置和获取所有数据成员的函数
Magnitude member function幅度成员函数
Angle member function (angle = inverse tangent(y / x))角度成员函数(角度 = 反正切(y / x))

ps I hope I am not doing anything wrong by uploading this and asking I have waited this entire time because I didn't want to break some sort of rule in the community....that I am honestly desperate to become a part of. ps我希望我上传这个并没有做错任何事情,并问我一直在等待,因为我不想打破社区中的某种规则......老实说,我非常渴望成为其中的一员。 I've dreamed of doing this my whole life and finally....ahh i digress sorry thanks guys我一生都梦想着这样做,最后......啊,我离题了,抱歉,谢谢大家

Oh...my code哦...我的代码

#include "Vertor.h"

#include <iostream>

int main()
{

    // creates a vector class
    Vector vector;

    vector.setXcom(4); // sets X
    vector.setYcom(12); // sets Y

    Vector vector1; // Creates another vector

    vector1.setXcom(3);
    vector1.setYcom(52);

    Vector vector2; // constructs another vector that returns the sum of two other vectors

    cout << vector.getXcom() << endl;
    cout << vector.getYcom() << endl;

    cout << vector.getMag() << endl;
    cout << vector.getAng() << endl;

    cout << vector1.getXcom() << endl;
    cout << vector1.getYcom() << endl;

    cout << vector1.getMag() << endl;
    cout << vector1.getAng() << endl;
}

#include<iostream> 
using namespace std;

// initalize variables
double xcomponent, ycomponent;
double ans, anns, annns;
class Vector // creates Vector class
    {
public:
    void setXcom(double x) // setX function
    {
        xcomponent = x;
    }

    void setYcom(double y) // setY function
    {
        ycomponent = y;
    }

    double getXcom() // getX function
    {
        return xcomponent;
    }

    double getYcom() // getY function
    {
        return ycomponent;
    }

    double getMag() // get magnitude function
    {
        double ans = sqrt((xcomponent * xcomponent) + (ycomponent * ycomponent));
        return ans;
    }

    double getAng() // get angle function
    {
        double annns = atan(xcomponent / ycomponent);
        return annns;
    }
    // setnewvec function to make a new vector from two others
    void setNewVec(int a, int b)
    {
        xcomponent = a;
        ycomponent = b;
    }
    // NOT SURE
    Vector getNewVec(int a, int b)
    {
        return a + a;
        return b + b;
    }
};

So you have an absolutely fundamental misunderstanding or gap in your knowledge about how objects work, and this task will be impossible until you sort that out.因此,您对对象如何工作的知识存在绝对根本的误解或差距,除非您解决这个问题,否则这项任务将是不可能的。

To illustrate here's a simpler example written in the style of your code above.为了说明这里的一个更简单的例子,用上面的代码风格编写。 I'll follow that with the same example written as it should be.我将按照应有的方式编写相同的示例。 This example is a simple Person class which has an age 'component'.这个例子是一个简单的Person类,它有一个年龄“组件”。

int age;

class Person
{
public:
    void setAge(int a) { age = a; }
    int getAge() { return age; }
};

int main()
{
    Person fred;
    fred.setAge(22);
    Person mary;
    mary.setAge(33);
    cout << "Fred is " << fred.getAge() << " and Mary is " << mary.getAge() << endl;
}

If you run this program the output will be Fred is 33 and Mary is 33 .如果你运行这个程序,输出将是Fred is 33 and Mary is 33 Both the people have the same age even though you set them as different in the program.即使您在程序中将他们设置为不同,这两个人的年龄也相同。

The problem is that although this program has two people it only has one age.问题是,虽然这个程序有两个人,但它只有一个年龄。 So it's literally impossible for the two people to have different ages.所以,两个人的年龄不同,几乎是不可能的。

Here's the program written correctly.这是正确编写的程序。 The crucial difference is that the age variable is inside the class .关键的区别在于age变量在 class 内部 This means that each Person object gets it's own age.这意味着每个Person对象都有自己的年龄。

class Person
{
public:
    void setAge(int a) { age = a; }
    int getAge() { return age; }
private:
    int age;
};

int main()
{
    Person fred;
    fred.setAge(22);
    Person mary;
    mary.setAge(33);
    cout << "Fred is " << fred.getAge() << " and Mary is " << mary.getAge() << endl;
}

Now the output is Fred is 22 and Mary is 33 as it should be.现在输出是Fred is 22 and Mary is 33应该Fred is 22 and Mary is 33

First thing you need to do, is to move xcomponent and ycomponent to inside the object.您需要做的第一件事是将xcomponentycomponent移动到对象内部。 Right now they are global variables which means they share values in all objects you create (and outside object too).现在它们是全局变量,这意味着它们在您创建的所有对象(以及外部对象)中共享值。

I'm gonna assume you've learned about structures before moving to objects.我假设您在移至对象之前已经了解了结构。 It's pretty hard to understand object without knowing structures first.如果不先了解结构,就很难理解对象。

Structures and classes are very similar.结构和类非常相似。 They both are containers for variables.它们都是变量的容器。 Classes are a little more advanced version that usually hides the raw data and instead provides member functions (sometimes called methods) that allow to manipulate the data inside in a more convenient way.类是更高级的版本,通常隐藏原始数据,而是提供成员函数(有时称为方法),允许以更方便的方式操作内部数据。

Anyway, when you create a new object of a class, you create it with a new copy all member variables (fields) inside.无论如何,当你创建一个类的新对象时,你创建了一个新的副本,里面的所有成员变量(字段)。 This way, they can have different values for each object.这样,它们可以为每个对象设置不同的值。

Your code is pretty easy to fix in that regard.在这方面,您的代码很容易修复。 Just move definition of these variables inside your class.只需在类中移动这些变量的定义即可。

Old code:旧代码:

double xcomponent, ycomponent;
double ans, anns, annns;
class Vector // creates Vector class
{
public:
   //...
};

New code:新代码:

class Vector // creates Vector class
{
    double xcomponent, ycomponent;
    double ans, anns, annns;
public:
   //...
};

Now we can work on the return value.现在我们可以处理返回值。

Your return value of getNewVec is all right.你的getNewVec返回值getNewVec You've declared that you want to return an object of type Vector and this is exactly what you want.您已经声明要返回Vector类型的对象,而这正是您想要的。 However, the function should also take a single vector as an argument.但是,该函数还应将单个向量作为参数。 Right now you have tho arguments int a and int b , none of which is a Vector .现在你有参数int aint b ,它们都不是Vector We need to change that to Vector otherVector to do what your assignment said.我们需要将其更改为Vector otherVector以执行您的任务所说的。

The call of the function looks like this: someVector.getNewVec(someOtherVector) .该函数的调用如下所示: someVector.getNewVec(someOtherVector) When it runs, you have two vectors accessible inside of it.当它运行时,您可以在其中访问两个向量。 The first of them is the one on which the function was called.其中第一个是调用函数的那个​​。 You have direct access to its fields.您可以直接访问其字段。 The second one is of course the argument otherVector .第二个当然是参数otherVector You can access its fields through its member functions.您可以通过其成员函数访问其字段。 (Or you can access directly its private fields because you're in a member function of its class.) (或者您可以直接访问其私有字段,因为您在其类的成员函数中。)

Now you need to construct the new vector.现在您需要构建新的向量。 The simplest way is to just create it and assign the values one by one:最简单的方法是创建它并一一赋值:

Vector getNewVec(Vector otherVector)
{
    Vector newVector;
    newVector.setXcom(xcomponent + otherVector.getXcom());
    newVector.setYcom(ycomponent + otherVector.getYcom());
    return newVector;
}

or:或者:

Vector getNewVec(Vector otherVector)
{
    Vector newVector;
    newVector.setXcom(xcomponent + otherVector.xcomponent);
    newVector.setYcom(ycomponent + otherVector.ycomponent);
    return newVector;
}

or if you really want:或者如果你真的想要:

Vector getNewVec(Vector otherVector)
{
    Vector newVector;
    newVector.setXcom(this->getXcom() + otherVector.getXcom());
    newVector.setYcom(this->getYcom() + otherVector.getYcom());
    return newVector;
}

( this is a pointer the object your inside of. You have access to it from each member function.) this是您内部对象的指针。您可以从每个成员函数访问它。)

I recommend the second option.我推荐第二种选择。


Some additional stuff you can read about if your interested... (I'm not gonna go into any details here.)如果您有兴趣,您可以阅读一些其他内容......(我不会在这里详细介绍。)

  1. Constructors You can have a special member function that is called when object it's created that is supposed to set initial values to the fields.构造函数 你可以有一个特殊的成员函数,它在创建对象时被调用,它应该为字段设置初始值。 It is written similar to a function, except is doesn't have a return value and it's name is always the same as the name of the class.它的编写类似于函数,除了它没有返回值并且它的名称始终与类的名称相同。
Vector(int x, int y)
{
    xcomponent = x;
    ycomponent = y;
}

That allows to create an abject and assign the values in one line so instead of:这允许创建一个对象并在一行中分配值,而不是:

Vector newVector;
newVector.setXcom(12);
newVector.setYcom(42);

you can have:你可以有:

Vector newVector(12, 42);

You can have more than one constructor with different list of arguments.您可以拥有多个具有不同参数列表的构造函数。

  1. You can create an operator instead of a normal function.您可以创建运算符而不是普通函数。 An operator is a function with specific name and arguments that can be called similarly to built-in mathematical operations.运算符是具有特定名称和参数的函数,可以类似于内置数学运算调用。 Operator for addition looks like this:加法运算符如下所示:
Vector operator+(Vector otherVector)
//the body is the same as getNewVec

You could call it like a normal member function:您可以像普通成员函数一样调用它:

someVector.operator+(someOtherVector)

but a better way of writing it is:但更好的写法是:

someVector + someOtherVector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM