通过类中的方法使用指针访问主要数组

huangapple go评论106阅读模式
英文:

Access array in main by pointers by method in class

问题

I need some help with my code, i prepare for my coming exam.

I have code with 3 classes: Package, Person and Courier(inherit from Person).
Then i have array in main with Packages.
And now i'm stuck at some point where i have 'Courier k1(p, p+3);' which means i need to assign to this Courier packages from p to p+3 by pointers. And my problem is that i don't know how to access this all packages i need by method from any class.
Simple example of code:

class Package
{
 string _address;
 float _value;
};

class Person
{
 string _name, _lastname;
};

class Courier:public Person
{
vector < Package > tab;
}

int main()
{
  Package p[] = {
    Package("Dabrowskiego 33", 123.00),
    Package("NMP 12", 40.00),
    Package("Armii Krakowej 4", 30.00),
    Package("Andersa 6", 51.00),
    Package("Kukuczki 13", 12.00),
    Package("Skrzyneckiego 5", 40.00),
  };
   Courier k1(p, p+3);
   cout << k1.value() << endl;
   
return 0;
};

Code above is only example, code in main is unchangeable because it's base from teacher.
I tried to make method in Courier with count amount of packages, and then add values to vector like this

for(int i=0;i<amount;i++)
            {
                tab.push_back(Package(*(p+i)));
            }

I dont know if it's a good way, even possible to do, but then i don't know how to display values by value() function.

Regards

Edit://

Thanks for help everyone, i managed to end my program and everything seems to work. But i have one doubt.

Courier k2;
  cout << "---- 8 ----" << endl;
  cout << k2.value() << endl;

  {
    Courier k3(k1);
    cout << "---- 9 ----" << endl;
    cout << k3.value() << endl;

    k2 = k3;
    cout << "---- 10 ----" << endl;
    cout << k2.value() << endl;

    k1 = k1 + p[4];
    k1 = k1 + p[5];

    cout << "---- 11 ----" << endl;
    cout << k1.value() << endl;

  }

  cout << "---- 12 ----" << endl;
  cout << k2.value() << endl;

Now i'm concerned. Right now values look like this:

  1. 8 - returns 0(as my default constructor set value to 0 if there is no value)
  2. 9 - returns 193 as it sums all values
  3. 10 - return same as above cuz it assign it from k3
  4. 11 - returns 245 because it add 2 values
  5. 12 - returns 193.

And now, should it work like this or values 8 and 12 should be the same (equal 0) and only values inside brackets should change?

英文:

I need some help with my code, i prepare for my coming exam.

I have code with 3 classes: Package, Person and Courier(inherit from Person).
Then i have array in main with Packages.
And now i'm stuck at some point where i have 'Courier k1(p, p+3);' which means i need to assign to this Courier packages from p to p+3 by pointers. And my problem is that i don't know how to access this all packages i need by method from any class.
Simple example of code:

class Package
{
 string _address;
 float _value;
};

class Person
{
 string _name, _lastname;
};

class Courier:public Person
{
vector &lt; Package &gt; tab;
}

int main()
{
  Package p[] = {
    Package(&quot;Dabrowskiego 33&quot;, 123.00),
    Package(&quot;NMP 12&quot;, 40.00),
    Package(&quot;Armii Krakowej 4&quot;, 30.00),
    Package(&quot;Andersa 6&quot;, 51.00),
    Package(&quot;Kukuczki 13&quot;, 12.00),
    Package(&quot;Skrzyneckiego 5&quot;, 40.00),
  };
   Courier k1(p, p+3);
   cout &lt;&lt; k1.value() &lt;&lt; endl;
   
return 0;
};

Code above is only example, code in main is unchangeable because it's base from teacher.
I tried to make method in Courier with count amount of packages, and then add values to vector like this

for(int i=0;i&lt;amount;i++)
            {
                tab.push_back(Package(*(p+i)));
            }

I dont know if it's a good way, even possible to do, but then i don't know how to display values by value() function.

Regards

Edit://

Thanks for help everyone, i managed to end my program and everything seems to work. But i have one doubt.

Courier k2;
  cout &lt;&lt; &quot;---- 8 ----&quot; &lt;&lt; endl;
  cout &lt;&lt; k2.value() &lt;&lt; endl;

  {
    Courier k3(k1);
    cout &lt;&lt; &quot;---- 9 ----&quot; &lt;&lt; endl;
    cout &lt;&lt; k3.value() &lt;&lt; endl;

    k2 = k3;
    cout &lt;&lt; &quot;---- 10 ----&quot; &lt;&lt; endl;
    cout &lt;&lt; k2.value() &lt;&lt; endl;

    k1 = k1 + p[4];
    k1 = k1 + p[5];

    cout &lt;&lt; &quot;---- 11 ----&quot; &lt;&lt; endl;
    cout &lt;&lt; k1.value() &lt;&lt; endl;

  }

  cout &lt;&lt; &quot;---- 12 ----&quot; &lt;&lt; endl;
  cout &lt;&lt; k2.value() &lt;&lt; endl;

Now i'm concerned. Right now values look like this:

  1. 8 - returns 0(as my default constructor set value to 0 if there is no value)
  2. 9 - returns 193 as it sums all values
  3. 10 - return same as above cuz it assign it from k3
  4. 11 - returns 245 because it add 2 values
  5. 12 - returns 193.

And now, should it work like this or values 8 and 12 should be the same (equal 0) and only values inside brackets should change?

答案1

得分: 2

Sure, here's the translated code part:

首先,Courier k1(p, p+3); 这一行代码表明类 Courier 有一个接受两个指针参数的构造函数。它会看起来像这样:

class Courier : public Person
{
public:
    Courier(const Package* first, const Package* last);
private:
    std::vector<Package> tab;
};

(如果你的课程还没有详细讨论const,在这个练习中可以安全地省略它,因为main 函数没有使用它。)

定义构造函数涉及初始化所有的基类和成员。在这种情况下,基类 Person 和成员 tab

这段代码没有提到姓和名,因此默认构造 Person 基类子对象是合理的。

幸运的是,std::vector<T> 已经有一个接受一对指针表示范围的构造函数。它是 cppreference 上的第五种,看起来是这样的:

template< class InputIt >
vector( InputIt first, InputIt last,
        const Allocator& alloc = Allocator() );

因为原始指针是一种输入迭代器类型。

所以构造函数的定义(如果在类定义之外编写)如下:

Courier::Courier(const Package* begin, const Package* end)
    : Person(),        /* 或者只需省略 Person() */
      tab(first, last) /* 将所有的 Package 复制到向量中 */
{}                     /* 在 tab 初始化完成后没有其他事情要做 */
英文:

First, the line Courier k1(p, p+3); implies that class Courier has a constructor which accepts two pointer arguments. That would look like:

class Courier : public Person
{
public:
    Courier(const Package* first, const Package* last);
private:
    std::vector&lt;Package&gt; tab;
};

(If your class hasn't discussed const much yet, you can probably safely leave it out for this exercise, since main doesn't use it.)

Defining a constructor involves initializing all the base classes and members. In this case, the base class Person and the member tab.

The code isn't saying anything about a first name or last name, so default-constructing the Person base subobject makes sense.

Luckily, std::vector&lt;T&gt; already has a constructor which takes a pair of pointers representing a range. It's #5 on cppreference, the one that looks like

template&lt; class InputIt &gt;
vector( InputIt first, InputIt last,
        const Allocator&amp; alloc = Allocator() );

since a raw pointer is a type of Input Iterator.

So the constructor definition (as it appears if written outside the class definition):

Courier::Courier(const Package* begin, const Package* end)
    : Person(),        /* or just omit the Person() */
      tab(first, last) /* copies all the Packages into the vector */
{}                     /* nothing else to do after tab is initialized */

答案2

得分: 1

Here is the translated code snippet:

如果您有一个指向对象的指针,您可以根据对象允许的内容来操作它。我认为您想要的是类似于

CourierPackage * currentPackage * end
{
    while (current= end) //循环直到结束。请注意,这可能会少一个。
                           //我不知道最后一个包是否应该添加
    {
        tab.push_back* current; //将当前包复制到向量中
        current ++; //前进到下一个包裹
    }
}

为什么

您没有“amount”,只有一个起始和结束,所以您从起始开始,查看所有直到结束的包裹(可能包括结束包裹,但这可能不太常见)。看起来您的教练可能正在尝试教迭代器。

注意:

Konrad在下面指出,这可以更智能地减少为构造“vector”:

CourierPackage * startPackage * end):tabstartend
{
}

这是填充“vector”的更聪明方法,但它不演示如何遍历指针,因此“不太教育”。

英文:

If you have a pointer to an object, you can do with it whatever the object will allow. What I think you want something like

Courier (Package * current, Package * end)
{
    while (current != end) // loop until the end. Note this could be off by one.
                           // I don&#39;t know id the last Package is supposed to be added
    {
        tab.push_back(*current); // copy current Package into vector
        current++; //advance to next Package
    }
}

Why

You don't have an amount, just a start and end, so you start at the start and look at all of the Packages up to the end (possibly including the end package, but this would be unusual). It looks like your instructor may be trying to teach iterators.

Note:

Konrad points out below that this can be reduced to constructing the vector more intelligently:

Courier (Package * start, Package * end):tab(start, end)
{
}

This is the smarter way to fill the vector, but it doesn't demonstrate how to iterate through the pointers so it's "less educational."

huangapple
  • 本文由 发表于 2020年1月7日 00:12:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定