给数组赋值

assigning value to an array

本文关键字:赋值 数组      更新时间:2023-10-16

这只是我正在尝试的代码大纲。请帮帮我!

void surfaceintensity(int xpos,int ypos ,int zpos)
{
    x[1]=xpos;
    x[2]=ypos;
    x[3]=zpos;
}

假设我有一个对象t1,并且我已经将值发送给函数surface intensity:

t1.surfaceintensity(10,20,30)

如果我按照上面的方法做,那么

的值是否会
x[1]=10;
x[2]=20;
x[3]=30;

如果不是,我如何将这些值分配给数组x[] ?

如果我理解正确的话,我认为我们的代码是您所期望的。但是你应该使用数组索引0..2个而不是1个……3个!

我理解你的问题的方式,你有一个类(我们称之为MyClass),它有一个成员函数surfaceintensity()。这个成员函数将一些值赋给数组x的元素,该数组也是你的类的成员。

你不确定从成员函数内部给数组赋值是否真的会改变它所调用的实例的数组。如果是这种情况,那么查看下面的示例(只需复制/粘贴它,它应该可以编译):

#include <iostream>
class MyClass
{
public:
    MyClass()
    {
        x[0] = 0;
        x[1] = 0;
        x[2] = 0;
    }
    void surfaceintensity(int xpos,int ypos ,int zpos)
    {
        x[0]=xpos;
        x[1]=ypos;
        x[2]=zpos;
    }
    void print()
    {
        std::cout << x[0] << "/" << x[1] << "/" << x[2] << std::endl;
    }
private:
    int x[3];
};
int main()
{
    MyClass t1;
    t1.print();
    t1.surfaceintensity(10,20,30);
    t1.print();
    return 0;
}

打印

0/0/0
10/20/30

这表明你的问题的答案是:是的,给成员变量赋值确实改变了对象的内部状态。

我希望这就是你要问的。如果没有,请编辑您的问题并澄清。