您好我试图使用继承调用来自不同类的对象成员,但编译器似乎抱怨。有替代方案吗?
我得到的错误是错误C2228:左边的' .func'必须有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
}
答案 0 :(得分:3)
有一些问题:
// 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();
}
答案 1 :(得分:0)
实际上“使用继承从不同的类调用对象成员”,基本函数已经具有该函数(它继承了该函数)
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();
使用::
答案 2 :(得分:0)
你应该有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;
}