使用函数访问和编辑多个类中的对象

问题描述 投票:0回答:1

我正在尝试在外部函数中使用两个类的对象,我可以将其调用到 main 中。我希望这个函数也使用方法来访问和编辑对象

#include <iostream>

using namespace std;

class Test
{
    private:
        int attrib;
        
    public:
        int getAttrib();
        void setAttrib(int);
        
        Test();
        
        //Test *object;
};

Test::Test()
{
    attrib = 0;
}

int Test::getAttrib()
{
    return attrib;
}

void Test::setAttrib(int _attrib)
{
    attrib = _attrib;
    cout << endl << "Test set opened" << endl;
}

class Test2
{
    private:
        char character;
        
    public:
        char getCharacter();
        void setCharacter(char);
        
        Test2();
        
        //Test2 *object2;
};

Test2::Test2()
{
    character = 'a';
}

char Test2::getCharacter()
{
    return character;
}

void Test2::setCharacter(char _character)
{
    character = _character;
    cout << endl << "Test2 set opened" << endl;
}

void setting(Test object, Test2 object2)
{
    cout << endl << "Success" << endl;
    
    object.setAttrib(1);
    object2.setCharacter('A');
    
    cout << object.getAttrib() << endl;
        cout << object2.getCharacter() << endl;
}

int main()
{
    Test object;
    Test2 object2;
    
    cout << "Construct: " << object.getAttrib() << " " << object2.getCharacter() << endl;
    
    setting(object, object2);
    
    cout << endl;
    
    cout << "Function: " << object.getAttrib() << " " << object2.getCharacter() << endl;
    
    object.setAttrib(2);
    object2.setCharacter('b');
    
    cout << endl;
    
    cout << "Method: " << object.getAttrib() << " " << object2.getCharacter() << endl;
    
    return 0;
}

现在程序输出对象,并且它们在函数中发生变化,但对象在函数外部不会发生变化

c++ dev-c++
1个回答
0
投票

您应该确保对象不仅在设置功能中发生变化: void 设置(测试 &object, Test2 &object2)

© www.soinside.com 2019 - 2024. All rights reserved.