c++函数能把对象作为参数吗?

2025-02-24 05:11:36
推荐回答(4个)
回答1:

类的对象、结构体的对象 都是可以作为函数的参数的。 struct tagStu{string m_strName;string m_strSex;}class CManage{void SetStu(tagStu stu){ // 结构体m_tagStu.m_strName = stu.m_strName;m_tagStu.m_strSex = stu.m_strSex;}public:void GetSex(){ return m_tagStu.m_strSex;}private:tagStu m_tagStu;}class TestB{ CManage m_mage; string GetSex(CManage &mg){ string strSex = msg.GetSex(); return strSex; }}

回答2:

C++是面向对象的体制,函数又是构成C/C++语言程序的最小模块,就是说C/C++语言程序就是由函数组成的。那么试想,如果C++的函数不能把对象作为传递参数,那C++的“面向对象”体制如何实现?所以C++的函数不仅可以以对象作为参数传递,而且方便得就像传递一个普通变量一样……

回答3:

可以把对象和结构体作为参数, 但是这就关系到深拷贝和浅拷贝的问题, 而且很影响效率,
你可以试试把对象参数改成引用类型, 或者指针类型

回答4:

class A{public:
    A()
    {
        cout << "construct" << endl;
    }    A(const A& a)
    {
        member = a.member;
        cout << "copy construct" << endl;
    }    A(A&& a)
    {        member = std::move(a.member);
        cout << "rvalue copy construct" << endl;
    }

    ~A()
    {
        cout << "destruct" << endl;
    }public:
    string member;};