c++ struct 结构体传递



#include<iostream>
using namespace std;
struct student
{
    string name;
    int age;
    int score;
};


class A{
public:
    A()
    {
      s = { "张三",30,80 };
    }

    student Get(){
        return s;
    }
    void Print()
    {
        std::cout  << s.age << " " << &s << " From Internal"  << std::endl;
    }

private:
    student s;
};

void printStudents(student s)
{
    // 做为参数传递时候时拷贝了一个新的, 原来的没有改变
    s.age = 20;
    std::cout  << s.age << " " << &s << " From Param"  << std::endl;
}

int main()
{
    A a;

    a.Print();
    printStudents(a.Get());
    a.Print();

    // 作为参数返回后拷贝了一个新的, 原来的没有改变
    student s = a.Get();
    s.age = 66;
    a.Print();
    std::cout  << s.age << " " << &s << " From Return"  << std::endl;

    system("pause");
    return 0;
}

输出log

30 0034FAA4 From Internal
20 0034FA4C From Param
30 0034FAA4 From Internal
30 0034FAA4 From Internal
66 0034FA80 From Return
请按任意键继续. . .
posted @ 2021-06-18 00:35  Onsunsl  阅读(302)  评论(0编辑  收藏  举报