有没有办法从嵌套类的函数中调用纯函数()?
G++返回错误:如果没有对象,则无法调用成员函数‘virtual void error::pure()’。
我不知道该怎么办。
class Outer
{
public:
class Nested
{
public:
void function();
};
public:
void print();
virtual void pure() = 0;
};
void Outer::print() {
printf("Hello! This is a test prgoram.\n");
}
void Outer::Nested::function()
{
Outer::pure(); // !!!!!! cannot call member function ‘virtual void Outer::pure()’ without object
printf("Function\n");
}
class D : Outer {
public:
void pure() override {
printf ("pure\n");
}
void d_function() {
printf ("d_function\n");
print();
}
};发布于 2020-03-27 15:18:24
要调用您的虚拟成员函数“pure”,您需要一个“D”的实例。有一个隐式隐藏参数(this)。如果不向函数传递所需的参数,则无法调用该函数。
您可以将参数添加到Nested::function:
class Nested
{
public:
void function(Outer& outer)
{
outer.pure();
}
};或者你可以存储一个引用:
class Nested
{
public:
Nested(Outer& outer) : outer{outer} {}
void function()
{
outer.pure();
}
private:
Outer& outer;
};对于第二个版本,您可以提供一个工厂函数:
class Outer
{
public:
class Nested
{
public:
Nested(Outer& outer) : outer{outer} {}
void function()
{
outer.pure();
}
private:
Outer& outer;
};
virtual void pure() = 0;
auto make_nested()
{
return Nested{*this};
}
};用法:
class Derived : public Outer
{
public:
void pure() override
{
printf ("pure\n");
};
};
int main()
{
Derived derived;
auto nested = derived.make_nested();
nested.function(); // calls pure
return 0;
}发布于 2020-03-27 16:27:15
不幸的是,这种用法是不可能的:-/。
我不能打电话:
Outer outer;类外部具有虚拟的void外部::pure()。
我的错误:
main.cpp: In function ‘int main()’:
main.cpp:130:11: error: use of deleted function ‘Outer::Outer()’
Outer outer;
^~~~~
main.cpp:81:7: note: ‘Outer::Outer()’ is implicitly deleted because the default definition would be ill-formed:
class Outer
^~~~~
main.cpp:81:7: error: no matching function for call to ‘Outer::Nested::Nested()’
main.cpp:87:13: note: candidate: Outer::Nested::Nested(Outer&)
Nested(Outer& outer) : outer{outer} {}
^~~~~~
main.cpp:87:13: note: candidate expects 1 argument, 0 provided
main.cpp:84:15: note: candidate: constexpr Outer::Nested::Nested(const Outer::Nested&)
class Nested
^~~~~~
main.cpp:84:15: note: candidate expects 1 argument, 0 provided
main.cpp:84:15: note: candidate: constexpr Outer::Nested::Nested(Outer::Nested&&)
main.cpp:84:15: note: candidate expects 1 argument, 0 provided
main.cpp:130:11: error: cannot declare variable ‘outer’ to be of abstract type ‘Outer’
Outer outer;
^~~~~
main.cpp:81:7: note: because the following virtual functions are pure within ‘Outer’:
class Outer
^~~~~
main.cpp:99:22: note: virtual void Outer::pure()
virtual void pure() = 0;https://stackoverflow.com/questions/60870590
复制相似问题