错误 C3662:覆盖说明符“new”只允许在托管类的成员函数上使用

发布于 2024-09-01 16:18:31 字数 783 浏览 3 评论 0原文

好的,所以我尝试重写父类中的函数,并收到一些错误。这是一个测试用例

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

归途 2024-09-08 16:18:31

无需在派生类中放置任何关键字来重写函数。

class B: public A{
    public:
    void printAba();
};

但基类的方法应该是虚拟的,以允许根据变量的实际身份来选择方法。

class A{
public:
    int aba;
    virtual void printAba();
};

如果您在堆栈上创建 B 并将其复制到 A 中,将会发生切片。您应该在堆上创建一个 B 并将指针强制转换为 A。

A* a = new B();
a->printAba();  // if printAba is not virtual, A::printAba will be called.
delete a;

There's no need to put any keywords in the derived class to override a function.

class B: public A{
    public:
    void printAba();
};

But the base class's method should be virtual, to allow the method be selected depending on the actual identity of the variable.

class A{
public:
    int aba;
    virtual void printAba();
};

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.

A* a = new B();
a->printAba();  // if printAba is not virtual, A::printAba will be called.
delete a;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文