【问题标题】:How to call a object member from different class?如何调用不同类的对象成员?
【发布时间】:2014-05-23 15:11:01
【问题描述】:

您好,我正在尝试使用继承从不同的类调用对象成员,但编译器似乎在抱怨。有没有替代方案?

我得到的错误是错误 C2228: left of '.func' must have class/struct/union

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
} 

【问题讨论】:

  • 但编译器似乎在抱怨。关于什么?
  • 错误 C2228: '.func' 的左边必须有类/结构/联合
  • 发布到问题中
  • 代码不是有效的 C++ 语法。 StackOverflow 不太适合作为学习 C++ 的教程站点。你不能在类声明的中间写像obj1.func()这样的表达式语句。

标签: c++ oop


【解决方案1】:

有几点不对:

// 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();
}

【讨论】:

  • 谢谢你,“myObject.obj1.func();”这是我不知道的
【解决方案2】:

你应该有一个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;
} 

【讨论】:

  • 谢谢你," obj2.obj1.func(); "这是我不知道的
【解决方案3】:

实际上“使用继承调用不同类的对象成员”,基函数已经具有该函数(它继承了该函数)

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();

使用 :: 调用时将其设为静态

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 2016-02-12
    相关资源
    最近更新 更多