如何从不同的类调用对象成员
How to call a object member from different class?
嗨,我正试图使用继承从不同的类调用对象成员,但编译器似乎有点抱怨。有其他选择吗?
我得到的错误是错误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();
使其为静态,以便使用::
进行调用
相关文章:
- 是什么让放置新调用对象的构造函数?
- 当我调用对象的方法时,对象的成员会发生变化
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 如何从构造函数副本 T(const T&)调用对象 T?
- C++17 如何保存泛型可调用对象以供以后使用
- 检查模板中 nullptr 的函数指针,了解任何类型的可调用对象
- 是否可以在编译时初始化对象的 C 样式函数指针,以便它调用对象的成员函数?
- 如何在C++中将可调用对象放入地图中?
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 广义 std::function (std::any 表示可调用对象)
- c++ 替换调用对象方法的宏函数
- 将可调用对象传递给采用 std::function 的构造函数
- 双指针在使用 new 时不调用对象构造函数
- 可调用对象作为默认模板参数
- 只需调用对象即可获取对象数据
- 如果用户尝试从 JS 调用对象的未定义函数C++则回调C++代码
- 如何将当前替代类型的 std::variant 传递给可调用对象?
- C++对象本身作为参数调用对象的方法
- 从移交的类调用对象