如何从不同的类调用对象成员

How to call a object member from different class?

本文关键字:调用 对象 成员      更新时间:2023-10-16

嗨,我正试图使用继承从不同的类调用对象成员,但编译器似乎有点抱怨。有其他选择吗?

我得到的错误是错误C2228:".func"的左侧必须具有类/结构/联合

class test
{
public: 
    void func()
    { 
        cout<<"test print"<<endl; // actually performing a complicated algorithm here
    }
};
class demo :public test
{
public: 
    test obj1;
    obj1.func();
};
void main()
{
    demo::obj1.func();// getting an error here
} 

有一些错误:

// This part is ok (assuming proper header/using)
class test
{
public: 
    void func(){ 
        cout<<"test print"<<endl; // actually performing a complicated algorithm here
    }
};
// You have demo inheriting from test. I don't think you want that
//class demo :public test
class demo
{
public: 
    test obj1;       // Ok
    // obj1.func();  // Not ok. You can't call a function in a class definition
};
void main()
{
    // There are no static functions. You need to create an object
    //demo::obj1.func();// getting an error here
    demo myObject;
    myObject.obj1.func();
}

或者,如果您想使用继承:

// This part is ok (assuming proper header/using)
class test
{
public: 
    void func(){ 
        cout<<"test print"<<endl; // actually performing a complicated algorithm here
    }
};
class demo : public test
{
public: 
    //test obj1;     // No need for this since you inherit from test
    // obj1.func();  // Not ok. You can't call a function in a class definition
};
void main()
{
    // There are no static functions. You need to create an object
    //demo::obj1.func();// getting an error here
    demo myObject;
    myObject.func();
}

您应该有一个demo实例。然后召集其成员。

#include <iostream>
#include <string>
using namespace std;
class test
{
public: 
    void func()
    { 
        cout<<"test print"<<endl; // actually performing a complicated algorithm here
    }
};
class demo :public test
{
public: 
    test obj1;
};
int main()
{
    demo obj2;
    obj2.obj1.func();
    return 1;
} 

事实上,"使用继承从不同类调用对象成员",基函数已经有了该函数(它继承了该函数(

class demo :public test
{
};
int main(int argc, char** argv)
{
  demo obj;
  obj.func();
}

你也可以做:

  • ;放在每个类的末尾
  • obj1.func()必须在另一个函数或其他函数中

尝试:

class demo :public test
{
public: 
test obj1;
demo() {obj1.func();}
};

class demo :public test
{
public: 
test obj1;
void callObj1Func() {obj1.func();}
};

并将其分别称为demo obj;demo obj; obj.callObj1Func();

使其为静态,以便使用:: 进行调用