错误 C3662:覆盖说明符“new”只允许在托管类的成员函数上使用
好的,所以我尝试重写父类中的函数,并收到一些错误。这是一个测试用例
#include <iostream>
using namespace std;
class A{
public:
int aba;
void printAba();
};
class B: public A{
public:
void printAba() new;
};
void A::printAba(){
cout << "aba1" << endl;
}
void B::printAba() new{
cout << "aba2" << endl;
}
int main(){
A a = B();
a.printAba();
return 0;
}
,这是我遇到的错误:
Error 1 error C3662: 'B::printAba' : override specifier 'new' only allowed on member functions of managed classes c:\users\test\test\test.cpp 12 test
Error 2 error C2723: 'B::printAba' : 'new' storage-class specifier illegal on function definition c:\users\test\test\test.cpp 19 test
我到底该怎么做?
Okay, so I'm trying to override a function in a parent class, and getting some errors. here's a test case
#include <iostream>
using namespace std;
class A{
public:
int aba;
void printAba();
};
class B: public A{
public:
void printAba() new;
};
void A::printAba(){
cout << "aba1" << endl;
}
void B::printAba() new{
cout << "aba2" << endl;
}
int main(){
A a = B();
a.printAba();
return 0;
}
And here's the errors I'm getting:
Error 1 error C3662: 'B::printAba' : override specifier 'new' only allowed on member functions of managed classes c:\users\test\test\test.cpp 12 test
Error 2 error C2723: 'B::printAba' : 'new' storage-class specifier illegal on function definition c:\users\test\test\test.cpp 19 test
How the heck do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无需在派生类中放置任何关键字来重写函数。
但基类的方法应该是虚拟的,以允许根据变量的实际身份来选择方法。
如果您在堆栈上创建 B 并将其复制到 A 中,将会发生切片。您应该在堆上创建一个 B 并将指针强制转换为 A。
There's no need to put any keywords in the derived class to override a function.
But the base class's method should be virtual, to allow the method be selected depending on the actual identity of the variable.
And if you create an B on stack and copy into A, slicing would occur. You should create a B on heap and cast the pointer as A.